python - 尝试从 Tkinter 比例尺中获取值并将其放入标签中

标签 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 接口(interface)完全一窍不通。 如果有人能解释我做错了什么,我会很高兴。

最佳答案

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

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

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

关于python - 尝试从 Tkinter 比例尺中获取值并将其放入标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17257045/

相关文章:

macos - 核心数据崩溃报告: sqlite3VdbeHalt in loading array controller

C#:继承派生类的单独静态成员

oop - MATLAB : Instantiate a class from an empty Instance to a 'Blank' Instance

java - 如何将我的返回方法与这段代码结合起来? (Java、Eclipse)

python - music21 --> stream.chordify() 不起作用

ruby - (Mac) 当语法设置为 Ruby 时 Vim 相当慢

python - 如何从 python 中的字典生成图形的邻接矩阵?

ios - 在 cocoa mac OS X 应用程序中在 facebook 和 twitter 中共享文本?

python - 如何向我的类添加类似于日期时间的自定义格式化程序?

python - 序列中的 n 个最大元素(需要保留重复项)