【问题标题】:How do I iterating throw list of lables in TKinter如何遍历 TKinter 中的标签列表
【发布时间】:2020-03-24 14:10:32
【问题描述】:

我正在尝试创建 18 x 18 的标签网格,并让每个标签都有一个 EnterLeave 事件。但是当我编写代码时,它只会为网格中的最后一个标签创建一个事件。我在这里没有得到什么?

附言 对不起,如果代码很乱,我学习 Python 才 1 个月

from tkinter import *
import string


root = Tk()


sequence_lst = list(string.ascii_letters)
execute = 0
num = 2

while execute < 3:
    for i in range(len(sequence_lst)):
        sequence_lst.append(sequence_lst[i]*num)
    execute += 1
    num += 1
sequence_lst = sequence_lst[:324]



position_x = 0
position_y = 0
square_lst = []
while position_x < 18:
    for i in range(18):
        if position_y < 18:
            square = Label(root, width=2, borderwidth=1, relief='solid')
            square.grid(row=position_x, column=position_y)
            position_y += 1
            square_lst.append(square)
        else:
            position_y = 0
            position_x += 1


for sequence in sequence_lst:
    sequence = square_lst[sequence_lst.index(sequence)]
    sequence.bind('<Enter>', lambda event: sequence.configure(bg='blue'))
    sequence.bind('<Leave>', lambda event: sequence.configure(bg='white'))        


root.mainloop()

【问题讨论】:

标签: python loops tkinter


【解决方案1】:

使用event.widget 更改您的绑定以引用与事件关联的小部件:

sequence.bind('<Enter>', lambda event: event.widget.configure(bg='blue'))
sequence.bind('<Leave>', lambda event: event.widget.configure(bg='white'))  

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 2019-09-16
    • 2015-05-14
    • 2013-08-28
    • 2016-10-14
    • 2023-01-31
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多