【发布时间】:2021-07-25 08:04:46
【问题描述】:
我正在尝试简化计算器的代码。
我没有为每个按钮编写代码,而是尝试将它们全部放在一个 for 循环中,但事实证明让按钮具有单独的命令是很困难的。
目前代码如下:
from tkinter import *
from functools import partial
win = Tk()
counter = 0
button_text = ("M", "(", ")", "C", "7", "8", "9", "-", "4", "5", "6", "+", "1", "2", "3", "*", "AC", "0", ".", "=")
button_ids = []
label = Label(text="Enter text here", )
label.grid(row=10, column=1, columnspan=4)
def click(n):
global label
# get index and ID of button
print(n)
button_name = (button_ids[n])
button_name.configure(text=f"clicked {button_ids[n]}")
label.config(text=f"{button_ids[n]} clicked")
for r in range(5):
for c in range(4):
# create buttons & assign unique arg (i) to run function (change)
button = Button(win, width=15, text=button_text[counter], command=partial(click, r))
button.grid(row=r, column=c)
# add ID to list
button_ids.append(button)
# update counter for next button text
counter += 1
print(button_ids)
win.mainloop()
只有一个 for 循环它可以工作,但添加第二个来创建数组,不会。
如何让每个按钮正常工作/注册?
【问题讨论】:
标签: python arrays tkinter button command