通过 tkinter 中的方法更改全局变量

Changing global variable via method in tkinter

我做了一些研究,发现要在 python 中的方法中更改全局变量,您必须传递 global variablename,然后继续使用该方法更改它。我试图根据 tkinter Optionmenu 选择将变量更改为 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' 来比较字符串。这是我修改后的代码,包括一些代码清理:

from tkinter import *

AllCheck = False
filterList = ["All","Not All"]

def check_dropdown(*args):
    global AllCheck
    AllCheck = FilterChoiceVar.get() == "All"

def scanBus():
    check_dropdown()
    if ScanVar.get() and AllCheck:
        print("AllCheck in action!")

GuiWindow = Tk()

FilterChoiceVar = StringVar(GuiWindow)
FilterChoiceVar.set("Not All")
FilterChoice = OptionMenu(GuiWindow, FilterChoiceVar, *filterList)
FilterChoice.grid(row=0, column=0)

ScanVar = BooleanVar()
ScanButton = Checkbutton(GuiWindow, text="scan", variable=ScanVar,
                         command=scanBus, indicatoron=0)
ScanButton.grid(row=1, column=0)

GuiWindow.geometry('{}x{}'.format(100, 60))
GuiWindow.mainloop()