带有tkinter TypeError的Pystray:接受1个位置参数,但给定2

时间:2019-03-18 00:35:30

标签: python python-3.x oop tkinter systray

通常,当我在没有对象的情况下编写代码时,我的tkinter程序将像这样:

from pystray import MenuItem as item
import pystray
from PIL import Image
import tkinter as tk

window = tk.Tk()
window.title("Welcome")

def quit_window(icon, item):
    icon.stop()
    window.destroy()

def show_window(icon, item):
    icon.stop()
    window.after(0,window.deiconify)

def withdraw_window():  
    window.withdraw()
    image = Image.open("image.ico")
    menu = (item('Quit', quit_window), item('Show', show_window))
    icon = pystray.Icon("name", image, "title", menu)
    icon.run()

window.protocol('WM_DELETE_WINDOW', withdraw_window)
window.mainloop()

我没有收到任何错误。但是当我用面向对象的代码编写程序时:

from pystray import MenuItem as item
import pystray
from PIL import Image
import tkinter as tk
class Program:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Welcome")
        self.window.protocol('WM_DELETE_WINDOW', self.withdraw_window)
        self.window.mainloop()

    def quit_window(self):
        self.icon.stop()
        self.window.destroy()

    def show_window(self):
        self.icon.stop()
        self.window.after(0, self.window.deiconify)

    def withdraw_window(self):
        self.window.withdraw()
        image = Image.open("microphone.ico")
        menu = (item('Quit', self.quit_window), item('Show', self.show_window))
        self.icon = pystray.Icon("name", image, "title", menu)
        self.icon.run()

run=Program()

当我单击退出时。我收到以下错误:

An error occurred when calling message handler
Traceback (most recent call last):
  File "D:\PythonInterpreter\Python37-32\lib\site-packages\pystray\_win32.py", line 378, in _dispatcher
    uMsg, lambda w, l: 0)(wParam, lParam) or 0)
  File "D:\PythonInterpreter\Python37-32\lib\site-packages\pystray\_win32.py", line 198, in _on_notify
    descriptors[index - 1](self)
  File "D:\PythonInterpreter\Python37-32\lib\site-packages\pystray\_base.py", line 240, in inner
    callback(self)
  File "D:\PythonInterpreter\Python37-32\lib\site-packages\pystray\_base.py", line 327, in __call__
    return self._action(icon, self)
  File "D:\PythonInterpreter\Python37-32\lib\site-packages\pystray\_base.py", line 421, in wrapper1
    return action(icon)
TypeError: quit_window() takes 1 positional argument but 2 were given

正如我在上面的两个示例中所展示的,问题出在pystray包中。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

好的。我解决了这个问题。我分享自己的代码以帮助他人。只需使用lambda函数:

public class MyAdapter extends XmlAdapter<Element, String> {

    @Override
    public Element marshal(String arg0) throws Exception {
        // do what you must
        return null;
    }

    @Override
    public String unmarshal(Element element) throws Exception {
        return element.getChildNodes().item(0).getNodeValue();
    }

}