Tkinter StringVar error

柔情痞子 提交于 2020-01-02 08:11:43

问题


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.

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.


回答1:


You need to specify the tk.StringVar(), as you did for every other tk function you specified.

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:

from tk import StringVar
from tk import *


来源:https://stackoverflow.com/questions/19983239/tkinter-stringvar-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!