Python-为什么不同的Tk标签显示为相同的坐标和不同的对象?
Python-Why does different Tk labels appear as same coordinate and as different objects?
我试图在 Python 中创建一些 Label
子类来告诉您它的 x 和 y 坐标。但是,当我查询 any 标签时,它总是 return (1,1)
,即使 Tk 对象不同。比如我点击了(2,2)
和(4,5)
标签,输出:
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和Y是一样的! (好吧,我可能点击了不同的坐标,但要注意的是标签不在同一个坐标上)
错误代码如下:
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()
怎么了?
在 location()
中使用 self.x
和 self.y
而不是 x
和 y
。我不会给你解释,因为我猜你只是忽略了它。
我试图在 Python 中创建一些 Label
子类来告诉您它的 x 和 y 坐标。但是,当我查询 any 标签时,它总是 return (1,1)
,即使 Tk 对象不同。比如我点击了(2,2)
和(4,5)
标签,输出:
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和Y是一样的! (好吧,我可能点击了不同的坐标,但要注意的是标签不在同一个坐标上)
错误代码如下:
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()
怎么了?
在 location()
中使用 self.x
和 self.y
而不是 x
和 y
。我不会给你解释,因为我猜你只是忽略了它。