我试图根据观察者信息放置一个变量。然后,我希望将此变量用于治疗中而不显示它。
#coding:utf-8
import tkinter
app = tkinter.Tk()
def CountryChoice(*args):
if observer.get() == 0:
Country = "France"
if observer.get():
Country = "United Kingdom"
observer = tkinter.StringVar()
observer.trace("w", CountryChoice)
FranceRadio = tkinter.Radiobutton(app, text="France", value=0, variable=observer)
UKRadio = tkinter.Radiobutton(app, text="UK", value=1, variable=observer)
FranceRadio .grid(row=0, column=0)
UKRadio .grid(row=0, column=1)
#def treaitement():
#i would like to reuse the variable Country here but I can not get it.
print(Country) #==> NameError: name 'Country' is not defined
app.mainloop()
目的是Country
当用户将鼠标放在按钮上时检索变量。下一个目标是添加一个启动按钮,该按钮将启动取决于单选按钮选择的过程。但是我无法获取Country
变量。
有几件事使您的问题中的代码无法正常工作。
NameError
之所以发生,是因为执行调用Country
时不存在全局变量print(Country)
。可以通过简单地预先定义变量(可能在脚本开头附近)来解决此问题。
与该问题有些相关的事实是,在CountryChoice()
函数中,Country
该变量被视为局部变量,因此在此处设置其值不会影响具有相同名称的全局变量。可以通过将变量声明global
为函数的开头来解决该问题。
最后,在使用Radiobutton
小部件时,value
选项的类型应与所使用的tkinter变量的类型匹配。在这种情况下,值是整数,因此我将变量类型observer
从从更改tk.StringVar
为tk.IntVar
。
我进行了这些更改,并在treatment()
函数末尾添加了对函数的调用,以在CountryChoice()
每次调用时打印当前值。
#coding:utf-8
import tkinter as tk
app = tk.Tk()
Country = None # Declare global variable.
def CountryChoice(*args):
global Country
if observer.get() == 0:
Country = "France"
elif observer.get() == 1:
Country = "United Kingdom"
treatment() # Use current value of Country.
observer = tk.IntVar() # Use IntVar since Radiobutton values are integers.
observer.trace("w", CountryChoice)
FranceRadio = tk.Radiobutton(app, text="France", variable=observer, value=0)
UKRadio = tk.Radiobutton(app, text="UK", variable=observer, value=1)
FranceRadio.grid(row=0, column=0)
UKRadio.grid(row=0, column=1)
def treatment():
# Reuse the variable Country.
print(Country)
app.mainloop()
最后,我想提出一些建议。我强烈建议您阅读并开始阅读PEP 8-Style Guide for Python Code的建议,特别是有关命名约定和代码布局的部分。这将使您的代码更易于使用和维护,也更易于他人阅读。
同样,问题的最佳答案是构造tkinter应用程序的最佳方法吗?tkinter专家对tkinter应用程序的最佳结构提出了一些极好的建议,如果您遵循它们,它们将消除使用大多数全局变量的需要(许多人认为这是不好的编程习惯)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句