Tkinter StringVar错误 [英] Tkinter StringVar error

查看:172
本文介绍了Tkinter StringVar错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此代码错误,未定义StringVar(),这可能是一件小事,但我对tkinter并不了解,希望获得帮助,谢谢。

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.

这是我的代码:

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

再次感谢。

推荐答案

您需要指定 tk.StringVar(),就像您对指定的其他所有tk函数一样。

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

self.variable = tk.StringVar()

这是因为您刚刚进行了导入tk 。另外,您也可以通过以下两行之一导入所需的功能,甚至全部输入:

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 *

这篇关于Tkinter StringVar错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆