[英]When using tkinter in Python 3, how do you get a button to run a function each time it is pressed?
import tkinter as tk
panel = tk.Tk()
num = 42
lbl1 = tk.Label(panel, text = str(num))
Let's say I have a function and button like this: 假设我有一个像这样的功能和按钮:
def increase():
lbl1.configure(text = str(num+1))
btn = tk.Button(panel, text = 'Increase', command = increase)
panel.mainloop()
This button will make the number that is the label increase by 1 when pressing the button. 按下按钮时,标签上的数字将增加1。 However, this only works once before the button does absolutely nothing. 但是,此操作仅在按钮完全不起作用之前起作用一次。 How can I make it so that every time I press the button, the number increases by 1? 如何使每次按下按钮时数字增加1?
You never saved the incremented value of num
. 您从未保存过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
It's because num is always 43 因为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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.