我尝试在Python中创建一些Label
子类来告诉您它的x和y坐标。但是,当我查询任何标签时,它总是返回(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
。我不给你解释,因为我猜你只是忽略了它。你知道吗相关问题 更多 >
编程相关推荐