【问题标题】:Global prefix not setting variable全局前缀未设置变量
【发布时间】:2021-11-30 00:55:54
【问题描述】:

我正在尝试制作一个 Tkinter 窗口,该窗口根据您单击的按钮设置变量。据我所知,这样做的唯一方法是将“命令”分配给一个函数。但是使用该变量的代码不在该函数中,因此我尝试使用“全局”来设置我想要选择的实际变量。但由于某种原因,它仍然返回 0,这是我最初设置的值。这是我的代码

        choi = 0
        def return1():
            global choi
            choi = '1'
            print(choi)
        def choicedone():
            choiwind.destroy()
        choiwind = tkinter.Tk()
        preset1_button = tkinter.Button(choiwind, text = 'button', command = return1)
        quit_button = tkinter.Button(choiwind, text = 'Done', command = choicedone)
        preset1_button.pack()
        quit_button.pack()
        choiwind.mainloop()
        print(choi)
        if choi == '1':
            #do stuff
        else:
            print('Error')

它返回“1”然后“0”然后“错误”

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    看起来发布的代码在函数内部,所以global choi 没有引用该函数内部的choi 变量。

    您需要将global choi 更改为nonlocal choi

    有关详细信息,请参阅globalnonlocal 上的 Python 文档。

    【讨论】:

      猜你喜欢
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多