Python tkinter trace error

让人想犯罪 __ 提交于 2021-02-05 08:25:53

问题


I'm trying to write a GUI for my code. My plan is to use tkinter's StringVar, DoubleVar, etc. to monitor my input in real time. So I found out the DoubleVar.trace('w', callback) function. However, every time I make the change I get an exception:

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

I have no idea what's going wrong. I'm using python 2.7 My code is as follows:

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() 

回答1:


Consider this line of code:

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

This is exactly the same as this:

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

Since the function returns None, the trace is going to try to call None, and thus you get 'NoneType' object is not callable

The trace method requires a callable. That is, a reference to a function. You need to change that line to be the following (notice the missing () at the end):

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

Also, you need to modify testfun to take arguments that are automatically passed by the tracing mechanism. For more information see What are the arguments to Tkinter variable trace method callbacks?



来源:https://stackoverflow.com/questions/44421642/python-tkinter-trace-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!