从类外部调用实例方法会导致崩溃

2024-07-08 09:58:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个包含wxwidgets(仅用于托盘图标)和Tkinter(用于GUI的其余部分)的应用程序。你知道吗

import wx
import Tkinter

TRAY_TOOLTIP = 'System Tray Icon'
TRAY_ICON = 'icon.png'

frm = False

class TaskBarIcon(wx.TaskBarIcon):
    def __init__(self):
        super(TaskBarIcon, self).__init__()
        self.set_icon(TRAY_ICON)
        self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)

    def set_icon(self, path):
        icon = wx.IconFromBitmap(wx.Bitmap(path))
        self.SetIcon(icon, TRAY_TOOLTIP)

    def on_left_down(self, event):
        createframe()

class Frame(Tkinter.Tk):
    def __init__(self, parent):
        Tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.protocol('WM_DELETE_WINDOW', self.closewindow)
        self.grid()

    def maximize(self):
        # supposed to try to hide and bring a window back up
        # full code removes the icon from the task bar, so I needed another way to make the window visible again
        self.withdraw()
        self.deiconify()

    def closewindow(self):
        self.destroy()
        global frm
        frm = False             

def createframe():
    global frm
    if isinstance(frm, Tkinter.Tk): # if a window is open, it goes through this if statement
        frm.maximize() # and crashes here.
    else:
        frm = Frame(None)
        frm.title('Frame')
        frm.mainloop()

def main():
    app = wx.App()
    TaskBarIcon()
    app.MainLoop()

if __name__ == '__main__':
    main()

您可以运行此代码并希望看到问题所在。当你用鼠标左键单击托盘图标时,会弹出一个窗口,你可以关闭它然后重新打开它,但是如果你最小化窗口(或者在窗口打开时只单击托盘图标),应用程序会崩溃。我想frm.maximize()就是问题所在,因为我可以在类中毫无困难地调用self.maximize(),但是我找不到解决方案。你知道吗

当我试图从TaskBarIcon类中执行frm.destroy()时,我也遇到了同样的问题(而frm.quit()工作得很好),所以这可能是一个提示?你知道吗


Tags: selfifinittkinterdefframetkparent

热门问题