使用函数调用对象方法

时间:2019-06-24 13:30:39

标签: python tkinter

我在tkinter周围玩耍,我想知道是否在对象中声明了一个方法,我可以使用tkinter的“协议”方法来调用它吗?或任何精确的函数,即。

class Notepad():
    ...
    ...
    def exit_func():
        #Messagebox command warning 'You are exiting'


root = tk.Tk()
notepad = Notepad(root)
root.geometry("800x500")

root.mainloop()

#Problem is here
root.protocol("WM_DELETE_WINDOW", app.exit_func())

我在我的程序中尝试了此操作,其中我的'exit_func'具有来自tkinter的'get'函数,并且出现了此错误:

Traceback (most recent call last):
File "Notepad_with_console.py", line 204, in <module>
root.protocol("WM_DELETE_WINDOW", notepad.exit_file())
File "Notepad_with_console.py", line 175, in exit_file
if self.text.get(1.0,tk.END) != '' and self.current_file_dir == '':
File "C:\Anaconda\lib\tkinter\__init__.py", line 3246, in get
return self.tk.call(self._w, 'get', index1, index2)
_tkinter.TclError: invalid command name ".!text"

这是有原因的吗?谢谢!

1 个答案:

答案 0 :(得分:2)

root.protocol需要对功能的引用。相反,您立即调用一个函数,然后传递结果。

考虑以下代码:

root.protocol("WM_DELETE_WINDOW", app.exit_func())

该代码在功能上与此相同:

result = app.exit_func()
root.protocol("WM_DELETE_WINDOW", result)

相反,您需要将引用传递给函数:

root.protocol("WM_DELETE_WINDOW", app.exit_func)