2013-11-14 114 views
2

嗨,我得到這個代碼StringVar()沒有定義的錯誤,它可能是一個小東西,但我不是與tkinter的經驗,並希望得到一些幫助,謝謝。Tkinter StringVar錯誤

這裏是我的代碼:

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 

感謝。

回答

2

您需要指定tk.StringVar(),就像您爲所指定的每個其他tk函數一樣。

self.variable = tk.StringVar() 

這是因爲你剛做了import tk。作爲替代方案,您可以通過以下兩行之一導入所需的功能,甚至所有功能:

from tk import StringVar 
from tk import * 
相關問題