Tkinter StringVar错误

时间:2013-11-14 16:38:24

标签: python string tkinter converter tk

嗨我得到一个错误,这个代码没有定义StringVar(),它可能是一个小东西,但我不是有经验的tkinter,并希望得到一些帮助,谢谢。

这是我的代码:

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()

这是错误:

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

再次感谢。

1 个答案:

答案 0 :(得分:4)

您需要像指定的每个其他tk函数一样指定tk.StringVar()

self.variable = tk.StringVar()

这是因为你刚刚做了import tk。作为替代方案,您可以通过以下两行之一导入您需要的功能,甚至所有功能:

from tk import StringVar
from tk import *