import tkinter as tk
panel = tk.Tk()
num = 42
lbl1 = tk.Label(panel, text = str(num))
我们说我有一个这样的功能和按钮:
def increase():
lbl1.configure(text = str(num+1))
btn = tk.Button(panel, text = 'Increase', command = increase)
panel.mainloop()
按下按钮时,此按钮将使标签的编号增加1。但是,这只能在按钮完全没有任何功能之前工作一次。我怎样才能使每次按下按钮时,数字增加1?
答案 0 :(得分:2)
您从未保存增加的num
。
def increase():
global num # declare it a global so we can modify it
num += 1 # modify it
lbl1.configure(text = str(num)) # use it
答案 1 :(得分:0)
这是因为num总是43
import tkinter as tk
num = 42
def increase():
global num
num += 1
lbl1.configure(text = str(num))
panel = tk.Tk()
lbl1 = tk.Label(panel, text = str(num))
lbl1.pack()
btn = tk.Button(panel, text = 'Increase', command = increase)
btn.pack()
panel.mainloop()