我做了一些研究,发现要在python中更改方法中的全局变量,必须传递global variablename
,然后继续用该方法更改它。我试图根据tkinter选项菜单选择将变量更改为true,但没有成功。我做错什么了?在
可验证的示例:
import tkinter
from tkinter import *
AllCheck = False
filterList = ["All"]
GuiWindow = Tk()
def change_dropdown(*args):
if FilterChoiceVar.get() is "All":
global AllCheck
AllCheck = True
return AllCheck
def scanBus():
change_dropdown()
if scanvar.get():
if AllCheck == True:
print("AllCheck in action!")
else:
pass
FilterChoiceVar = StringVar(GuiWindow)
FilterChoiceVar.set("All")
FilterChoice = OptionMenu(
GuiWindow, FilterChoiceVar, *filterList)
scanvar = BooleanVar()
scanbtn = Checkbutton(
GuiWindow,
text="scan",
variable=scanvar,
command=scanBus,
indicatoron=0)
scanbtn.grid(row=1, column=0)
FilterChoice.grid(row=0, column=0)
GuiWindow.geometry('{}x{}'.format(100, 50))
GuiWindow.mainloop()
主要问题来自于
FilterChoiceVar.get() is "All"
表达式,它永远不是真的。一个好的做法是始终使用“==”而不是“is”来比较字符串。以下是我修改的代码,包括一些代码清理:相关问题 更多 >
编程相关推荐