Python Tkinter StringVar 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19983239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tkinter StringVar error
提问by user2992997
Hi i get an error with this code that StringVar() is not defined, and its probably a small thing but i am not that experienced with tkinter and would like some help, thanks.
嗨,我收到此代码的错误,即 StringVar() 未定义,这可能是一件小事,但我对 tkinter 没有经验,需要一些帮助,谢谢。
Here's my code:
这是我的代码:
import tkinter as tk
class Converter1(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.variable = StringVar()
self.variable.set("Miles to Kilometers") # default dropdown menu value
self.menu = tk.OptionMenu(self, variable, "Miles to Kilometers", "Kilometers to Miles")
self.button = tk.Button(self, text="Convert!", command=self.convertMK)
self.button.pack()
self.menu.pack()
self.button.pack()
self.entry.pack()
def convtertMK(self): # converts the miles and kilometers using the dropdown menu
if var.get() == "Miles to Kilometers":
print(int(self.entry.get()) * 1.6093)
else:
print(int(self.entry.get()) / 1.6093)
converter = Converter1()
Here's the error:
这是错误:
Traceback (most recent call last):
File "/Users/MaxBookPro/Desktop/test.py", line 25, in <module>
converter = Converter1()
File "/Users/MaxBookPro/Desktop/test.py", line 8, in __init__
self.variable = Variable1
NameError: global name 'Variable1' is not defined
Thanks again.
再次感谢。
采纳答案by PearsonArtPhoto
You need to specify the tk.StringVar(), as you did for every other tk function you specified.
您需要指定tk.StringVar(),就像您为您指定的每个其他 tk 函数所做的那样。
self.variable = tk.StringVar()
This is because you just did an import tk. As an alternative, you could import just the functions you need, or even all of them, by one of the two following lines:
这是因为你刚刚做了一个import tk. 作为替代方案,您可以通过以下两行之一仅导入您需要的功能,甚至导入所有功能:
from tk import StringVar
from tk import *

