python - 如何在 TKinter 中迭代标签的抛出列表
问题描述
我正在尝试创建 18 x 18 的标签网格,并让每个标签都有一个Enter
和Leave
事件。但是当我编写代码时,它只会为网格中的最后一个标签创建一个事件。我没有得到什么?
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()
解决方案
更改绑定以引用与事件关联的小部件,使用event.widget
:
sequence.bind('<Enter>', lambda event: event.widget.configure(bg='blue'))
sequence.bind('<Leave>', lambda event: event.widget.configure(bg='white'))
推荐阅读
- java - Cypher 使用不在实体中的参数创建查询
- node.js - 等待 rxjs 可观察的完成缓冲区数据
- python - 从外部输入实时更新 Kivy ProgressBar
- mysql - 在 MySQL 中计算 CASE 语句中的空文本字段
- python - 如何在 odoo 12 中设置默认公司徽标?
- python - Scrapy + Python,返回多个项目,问题阅读页面
- android - 如何将值从 observable 返回到 JavascriptInterface 方法?
- python - 如何将列表中的所有整数返回为格式化字符串?
- bash - 用 cut 过滤“dmesg -w”
- javascript - 如何在节点js中对数组进行排序