Python 尝试从Tkinter标尺获取值并将其放入标签中

Python 尝试从Tkinter标尺获取值并将其放入标签中,python,macos,class,tkinter,python-2.5,Python,Macos,Class,Tkinter,Python 2.5,我有一个小Python程序,它获取Tkinter scale的值并将其放入标签中 #!/usr/bin/python from Tkinter import * class App: strval = StringVar() def __init__(self,master): frame = Frame(master) frame.pack() self.slide = Scale(frame, command = sel

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

#!/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
回溯(最近一次呼叫最后一次):
文件“/Users/alex/Desktop/Python/Tkinter/scale_Entry.py”,第5行,在
类应用程序:
文件“/Users/alex/Desktop/Python/Tkinter/scale_Entry.py”,第7行,应用程序中
strval=StringVar()
文件“/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py”,第254行,在__
变量。\uuuu init\uuuuu(self、master、value、name)
文件“/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py”,第185行,在__
self.\u tk=master.tk
AttributeError:“非类型”对象没有属性“tk”
Exception exceptions.AttributeError:“StringVar实例在已忽略的
注销
我不太确定到底出了什么问题,我完全不懂Tk接口。
我希望有人能解释一下我做错了什么。

之所以会这样,是因为您在创建Tk根元素之前创建了StringVar。如果将语句
root=Tk()

但是,理想的解决方案是以一种不依赖于顺序的方式编写它,因此我建议您在构造函数中创建StringVar:

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

这是因为您在创建Tk根元素之前创建了StringVar。如果将语句
root=Tk()

但是,理想的解决方案是以一种不依赖于顺序的方式编写它,因此我建议您在构造函数中创建StringVar:

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