The procedure is as follows:
import tkinter as tk
window = tk.Tk()
window.title("我的程序")
window.geometry('400x300')
var = tk.StringVar()
lable = tk.Label(window,textvariable = var,font = (('微软雅黑'),12))
lable.pack()
on_hit = True
def run():
global on_hit
if on_hit == True:
on_hit = False
var.set('you hit me')
else:
on_hit = True
var.set('')
button = tk.Button(window,text = 'hit',font = (('微软雅黑'),12),command = run)
button.pack()
window.mainloop()
The effect of this program is that there is a button. When you press it, you hit me will appear. Press it again and it will disappear. This cycle
Why is the button written as button = tk.Button(window, text = 'Generate questions and answers' , font = (('Microsoft Yahei'),12), command = run()), add parentheses when calling the function, press the button again, it will always be you hit me, and the content in the label above will no longer change. ?
In this sentence, just save the button by the run function itself and it will be automatically called after the button is clicked (equivalent to running run()
The interpreter will immediately callafter clicking).
If changed torun()
when it sees this sentence, and then save the return value of the
call to the button. Now the return value is called after the button is clicked (in this example it is None ).command can be called in two ways:
b = Button(... command = button)
b = Button(... command = lambda: button('hey'))
If you want to use () to call, you can use lambda to write:
button = tk.Button(window, text = 'Generate questions and answers', font = (('Microsoft Yahei'),12), command =lambda: run())