尝试从Tkinter量表获取值并将其放入Label中 [英] Trying to get the value from a Tkinter scale and put it into a Label

查看:193
本文介绍了尝试从Tkinter量表获取值并将其放入Label中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小型的Python程序,该程序采用Tkinter标度的值并将其放入标签中.

I have a small Python program that takes the value of a Tkinter scale and puts it into a label.

#!/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()

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

When I run the program it gives me and error message:

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

I'm not too sure what is going wrong and I'm completely crap at Tk interfacing. I would love if someone could explain what I'm doing wrong.

推荐答案

之所以会这样,是因为您在创建Tk根元素之前先创建StringVar.如果将语句root = Tk()移到类的定义之前,则会看到它的工作原理.

That happens because you are creating the StringVar before creating the Tk root element. If you move the statement root = Tk() before the definition of the class, you'll see how it works as expected.

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

However, the ideal solution would be write it in a way that you don't depend on the order to make it work, so I'd suggest you to create the StringVar in the constructor:

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

这篇关于尝试从Tkinter量表获取值并将其放入Label中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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