首页 > 解决方案 > 如何在 TKinter 中迭代标签的抛出列表

问题描述

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

ps 对不起,如果代码很乱,我只有 1 个月的时间来学习 Python

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()

标签: pythonloopstkinter

解决方案


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

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

推荐阅读