Tkinter:单击按钮时,函数中的全局似乎不起作用



单击按钮后,我希望varstateTrue

这是代码

from tkinter import *
root = Tk()
def value():
global state
state = True
print(state)
btn_choose_mouse_position = Button(root, text=' Choose click positions', fg='black', bg="green",
activebackground='#6D8573', command=value, padx=20, pady=20).pack()
try: print(state)
except:
pass
try:
if state:
print('works')
except:
pass
root.mainloop()

当我单击该按钮时,只打印该功能中的True

我找到了一种使用lambada将varstate设置为True的方法

from tkinter import *
root=Tk()
state = BooleanVar()
btn_choose_mouse_position = Button(root, text=' Choose click positions', fg='black', bg="green",
activebackground='#6D8573', command=lambda : state.set(True), padx=20, pady=20)
btn_choose_mouse_position.pack()
btn_choose_mouse_position.wait_variable(state)
root.mainloop()

state = BooleanVar()使state成为没有TrueFalsebool

.wait_variable(state)等待bool更改,有点像os.wait[在此处输入链接描述]

最新更新