繁体   English   中英

尝试从Tkinter标度中获取值并将其放入Label中

[英]Trying to get the value from a Tkinter scale and put it into a Label

我有一个小的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接口。 如果有人可以解释我在做什么错,我很乐意。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM