I tried to create some Label subclass in Python to tell you its x and y coordinates. However, when I queried any label, it would always return (1,1), even though the Tk objects are different. For example, I clicked the (2,2) and (4,5) labels, the output:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
============================== RESTART: C:/program.py==============================
(1, 1)
.53825904
(1, 1)
.53826736
>>>
X and Y are the same, even though objects are different! (OK, I might have clicked a different coordinate, but what's to care is that the labels are not on the same coordinate)
Here is the faulty code:
try:
from tkinter import * # Py3
except ImportError:
from Tkinter import * # Py2
class _MyLabel(Label):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.x = None
self.y = None
def grid(self, x, y):
self.x = x
self.y = y
super().grid(row=y, column=x)
def location(self):
return (7 - x + 1, 7 - y + 1)
def gen():
pass
def check(event):
print(event.widget.location())
print(event.widget)
print()
root = Tk()
sqs = [[_MyLabel(root, height=1, width=2, relief=SUNKEN, bg='white') for i in range(8)] for i in range(8)]
seq = []
for x in range(8):
for y in range(8):
sqs[y][x].grid(x, y)
sqs[y][x].bind('<Button-1>', check)
mainloop()
What's wrong?
Use self.x and self.y in location() instead of x and y. I will spare you an explanation because I guess you just overlooked it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With