Python 通过添加到变量编号来调用函数中的变量?
我正在tkinter中创建一个gui,并有名为btn1 btn2 btn3等的按钮,我希望按钮在单击时执行的操作是禁用单击的按钮并依次启用下一个按钮。我可以写出6个独立的函数,但这似乎违背了函数的意义Python 通过添加到变量编号来调用函数中的变量?,python,function,variables,tkinter,Python,Function,Variables,Tkinter,我正在tkinter中创建一个gui,并有名为btn1 btn2 btn3等的按钮,我希望按钮在单击时执行的操作是禁用单击的按钮并依次启用下一个按钮。我可以写出6个独立的函数,但这似乎违背了函数的意义 if (btn1['state'] == tk.NORMAL): btn1.config(state=tk.DISABLED), btn2.config(state=tk.NORMAL) else: print ('already clicked'
if (btn1['state'] == tk.NORMAL):
btn1.config(state=tk.DISABLED),
btn2.config(state=tk.NORMAL)
else: print ('already clicked')
这就是我现在拥有的,但我希望它看起来更像btn#+1(state=DISABLED)您可以将按钮放在列表中,然后在列表上迭代 这里有一个做作的例子:
import tkinter as tk
root = tk.Tk()
def click(button_number):
button = buttons[button_number]
button.configure(state="disabled")
if button == buttons[-1]:
# user clicked the last button
label.configure(text="BOOM!")
else:
next_button = buttons[button_number+1]
next_button.configure(state="normal")
next_button.focus_set()
label = tk.Label(root, text="")
label.pack(side="bottom", fill="x")
buttons = []
for i in range(10):
state = "normal" if i == 0 else "disabled"
button = tk.Button(root, text=i+1, state=state, width=4,
command=lambda button_number=i: click(button_number))
button.pack(side="left")
buttons.append(button)
buttons[0].focus_set()
root.mainloop()
您不需要
其他
。如果禁用了按钮
,则单击按钮时不会调用其命令。这意味着您也不需要if
。如果调用该命令,则状态必须为正常。