python - 我如何在 tkinter 中创建一组带有循环的按钮?
问题描述
我有这个程序我正在尝试创建,基本上我需要在 tkinter 中制作 8 行按钮,但我不知道如何使用循环来做到这一点,没有循环我这样做了:
def decimal():
app = Toplevel(root)
app.title("Traducteur décimal")
app.geometry("400x200")
r1 = Button(app, text="LED 1 ON")
r2 = Button(app, text="LED 1 OFF")
r1.place(x=125,y=0)
r2.place(x=225,y=0)
r3 = Button(app, text="LED 2 ON")
r4 = Button(app, text="LED 2 OFF")
r3.place(x=125, y=40)
r4.place(x=225, y=40)
r5 = Button(app, text="LED 3 ON")
r6 = Button(app, text="LED 3 OFF")
r5.place(x=125, y=80)
r6.place(x=225, y=80)
顺便说一句,我很抱歉英语不好。谢谢
解决方案
一种方法是将它们全部放在一个循环中list
。作为一个列表,你可以通过索引访问它的元素:2-tuples
for
buttons = []
x_loc_on, x_loc_off = (125, 225)
y_start = 0
y_offset = 40
commands = [<16 functions here>]
for row in range(8):
# calculate the pair's y-position based on row
y_pos_of_row = y_start + row * y_offset
# get the row number (starts from 1 unlike the variable `row`; so adding 1)
row_number = row + 1
# generate the ON button
button_1 = Button(app, text=f"LED {row_number} ON", command=commands[row])
button_1.place(x=x_loc_on, y=y_pos_of_row)
# generate the OFF button
button_2 = Button(app, text=f"LED {row_number} OFF", command=commands[row+1])
button_2.place(x=x_loc_off, y=y_pos_of_row)
# put this row's ON-OFF button pair as a 2-tuple into a list
buttons.append((button_1, button_2))
然后,您可以通过 访问i
行和ON
按钮,buttons[i][0]
并通过 访问同一行OFF
按钮buttons[i][1]
。
推荐阅读
- python - 如何使查看模型的权限只能由所属用户更新?
- doctrine-orm - 如何在多对一关系中手动加入列和目标实体?
- spring-boot - 如何使用@PostConstruct 仅在一个实例中调用@Scheduled 方法
- javascript - 使不是子元素的元素在悬停时显示
- amazon-web-services - 在 greengrass 核心 AWS 上运行 mqtt 代理
- javascript - 了解 useState 挂钩行为
- docker - 使用 azure CI-CD 将 docker 部署到本地
- python - 熊猫读取特定数量的列,而与数据文件无关
- python - 在 VS Code 中调试时如何解决“ImportError: cannot import”?
- java - JUnit:无法解析 obj