试图从Tkinter比例中获取值并将其放入Label中

时间:2013-06-23 01:55:21

标签: python macos class tkinter python-2.5

我有一个小的Python程序,它取一个Tkinter比例的值并将其放入标签中。

#!/usr/bin/python

from Tkinter import *

class App:

    strval = StringVar()
    def __init__(self,master):

        frame = Frame(master)
        frame.pack()
        self.slide = Scale(frame, command = self.up, from_ = 1, to = 100)
        self.out = Label(frame, textvariable = self.strval)
        self.slide.pack()
        self.out.pack()

    def up(self,newscale):
        amount = str(newscale)
        self.strval.set(amount)


root = Tk()
app =  App(root)
root.mainloop()

当我运行程序时,它会给我并输出错误消息:

Traceback (most recent call last):
  File "/Users/alex/Desktop/Python/Tkinter/scale_Entry.py", line 5, in <module>
    class App:
  File "/Users/alex/Desktop/Python/Tkinter/scale_Entry.py", line 7, in App
    strval = StringVar()
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py", line 254, in __init__
    Variable.__init__(self, master, value, name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py", line 185, in __init__
    self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
Exception exceptions.AttributeError: "StringVar instance has no attribute '_tk'" in <bound method StringVar.__del__ of <Tkinter.StringVar instance at 0x69f238>> ignored
logout

我不太确定会出现什么问题,而且我对Tk接口完全不知所措。 如果有人能解释我做错了什么,我会很高兴。

1 个答案:

答案 0 :(得分:5)

这是因为您在创建Tk根元素之前创建了StringVar。如果您在类的定义之前移动语句root = Tk(),您将看到它如何按预期工作。

然而,理想的解决方案是以不依赖于顺序的方式编写它以使其工作,所以我建议你在构造函数中创建StringVar:

class App:
    def __init__(self,master):
        frame = Frame(master)
        frame.pack()
        self.strval = StringVar(frame)
        # ...