用tkin中的方法改变全局变量

2024-09-27 23:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一些研究,发现要在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()

Tags: 方法importgetiftkinterdefallchange
1条回答
网友
1楼 · 发布于 2024-09-27 23:17:30

主要问题来自于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()

相关问题 更多 >

    热门问题