gpt4 book ai didi

Python-为什么不同的Tk标签显示为相同的坐标和不同的对象?

转载 作者:行者123 更新时间:2023-11-28 18:32:44 24 4
gpt4 key购买 nike

我尝试在 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.xself.y 而不是 x y。我不会向您解释,因为我猜您只是忽略了它。

关于Python-为什么不同的Tk标签显示为相同的坐标和不同的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35328027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com