PythonWhy不同的Tk标签显示为相同的坐标和不同的对象?

2024-05-20 00:01:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在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()

怎么了?你知道吗


Tags: 对象infromimportselfeventfordef