【问题标题】:Python tkinter trace errorPython tkinter 跟踪错误
【发布时间】:2017-06-07 19:52:31
【问题描述】:

我正在尝试为我的代码编写 GUI。我的计划是使用tkinter的StringVarDoubleVar等来实时监控我的输入。所以我发现了DoubleVar.trace('w', callback) 函数。但是,每次我进行更改时都会出现异常:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Anaconda2\lib\lib-tk\Tkinter.py", line 1542, in __call__
    return self.func(*args)
TypeError: 'NoneType' object is not callable

我不知道出了什么问题。我正在使用 python 2.7 我的代码如下:

from Tkinter import *
class test(Frame):
    def __init__(self,master):
        Frame.__init__(self,master=None) 
        self.main_frame = Frame(master);
        self.main_frame.pack() 
        self.testvar = DoubleVar()
        self.slider_testvar = Scale(self.main_frame,variable = self.testvar,from_ = 0.2, to = 900, resolution = 0.1, orient=HORIZONTAL,length = 300)
        self.slider_testvar.grid(row = 0, column = 0, columnspan = 5)       
        self.testvar.trace('w',self.testfun())    
    def testfun(self):
        print(self.testvar.get())

root = Tk()
root.geometry("1024x768")
app = test(master = root) 
root.mainloop() 

【问题讨论】:

  • 我无法在 Ubuntu 16.04 上使用 Python 2.7 进行复制。一切都对我有用。你确定这是你所有的代码吗?
  • 将您的跟踪更改为self.testvar.trace('w', self.testfun) 以防止执行声明和定义您的回调到def testfun(self, *args): 以提供多个参数。链接:similar problemtrace callback arguments
  • @CommonSense 你能在上面的评论中发布你的答案作为答案吗?那么它可以被“接受”吗?
  • @CommonSense,非常感谢,你拯救了我的一天。

标签: python python-2.7 tkinter trace


【解决方案1】:

考虑这行代码:

self.testvar.trace('w',self.testfun())  

这和这个完全一样:

result = self.testfun()
self.testvar.trace('w', result)

由于函数返回None,跟踪将尝试调用None,因此你得到'NoneType' object is not callable

trace 方法需要一个可调用的。也就是对函数的引用。您需要将该行更改为以下内容(注意末尾缺少 ()):

self.testvar.trace('w',self.testfun) 

此外,您需要修改testfun 以获取跟踪机制自动传递的参数。欲了解更多信息,请参阅What are the arguments to Tkinter variable trace method callbacks?

【讨论】:

  • 非常感谢
  • @Bryan Oakley 你是耐心的大师。我觉得三分之一的 tkinter 问题正是这个问题
  • @Jannick:肯定有很多 与调用函数相关的问题,而不是提供参考。问题是,对于初学者程序员来说,这是一个有点难以理解的概念。
猜你喜欢
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多