Скрытие меню в WxPython - PullRequest
0 голосов
/ 12 января 2020

Я пытаюсь найти способ скрыть строку меню, когда мышь не находится над ней, я знаю, что могу получить положение мыши xy и проверить, находится ли она в определенной области, но мне не повезло, скрывая строку меню. Мой код:


class HelloFrame(wx.Frame):
    images = []

    def __init__(self, *args, **kw):
        # ensure the parent's __init__ is called
        super(HelloFrame, self).__init__(*args, **kw)

        # create a panel in the frame
        pnl = wx.Panel(self)

        # create a menu bar
        self.makeMenuBar()

        # and a status bar
        #self.CreateStatusBar()
        #self.SetStatusText("Welcome to wxPython!")


    def makeMenuBar(self):

        fileMenu = wx.Menu()
        helloItem = fileMenu.Append(-1, "&Load Backround Image")
        fileMenu.AppendSeparator()
        exitItem = fileMenu.Append(wx.ID_EXIT)
        helpMenu = wx.Menu()
        aboutItem = helpMenu.Append(wx.ID_ABOUT)
        menuBar = wx.MenuBar()
        menuBar.Append(fileMenu, "&File")
        #menuBar.Append(OptionsMenu, "&Options") TBM
        menuBar.Append(helpMenu, "&Help")

        # Give the menu bar to the frame
        self.SetMenuBar(menuBar)

        # Finally, associate a handler function with the EVT_MENU event for
        # each of the menu items. That means that when that menu item is
        # activated then the associated handler function will be called.
        self.Bind(wx.EVT_MENU, self.OpenImage, helloItem)
        self.Bind(wx.EVT_MENU, self.OnExit,  exitItem)
        self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)



    def OnExit(self, event):
                self.Close(True)

    def OnAbout(self, event):
        wx.MessageBox("Test",
                      "About",
                      wx.OK|wx.ICON_INFORMATION)

    def OpenImage(self, event):
        with wx.FileDialog (None, "Choose image", wildcard="PNG files (*.png)|*.png", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return       # the user changed their mind
            else:
                # Gets rid of other images
                for i in self.images:
                    i.Destroy()
                    self.images.remove(i)

                # Displays image and adds image object to [self.images]
                ImageName = fileDialog.GetPath()
                png = wx.Image(ImageName, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
                self.images.append(wx.StaticBitmap(self, -1, png, (0, 0), (png.GetWidth(), png.GetHeight())))
                print(ImageName)


if __name__ == '__main__':
    app = wx.App()
    frm = HelloFrame(None, title='FileHeader Test')
    frm.Show()
    app.MainLoop()

Я попытался просто добавить menubar.Hide () в функцию makemenubar, но безрезультатно, я также попытался self.Hide () в той же области, но не повезло

1 Ответ

0 голосов
/ 13 января 2020

Мне следует начать с того, что я не рекомендую вам это делать.
Это нестандартно и может привести к путанице.
Это дорого в плане производительности без очевидной выгоды.

Тем не менее, вот один из способов сделать это, используя Show, Hide и EVT_MOTION.
Проблема в том, что, как только она будет скрыта / удалена, следующая мышь OVER не происходит, потому что его больше нет. Как вы предполагаете, мы можем назначить территориальный диапазон, где мы предполагаем, что это будет. Если курсор перемещается в эту зону, меню можно показать или скрыть.

import wx

class HelloFrame(wx.Frame):
    images = []

    def __init__(self, *args, **kw):
        # ensure the parent's __init__ is called
        super(HelloFrame, self).__init__(*args, **kw)
        # create a panel in the frame
        pnl = wx.Panel(self)
        pnl2 = wx.Panel(self)
        pnl.SetBackgroundColour("green")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(pnl,1, wx.EXPAND,10)
        sizer.Add(pnl2,1, wx.EXPAND,10)
        self.SetSizer(sizer)

        # create a menu bar
        self.makeMenuBar()

        # and a status bar
        #self.CreateStatusBar()
        #self.SetStatusText("Welcome to wxPython!")
        pnl.Bind(wx.EVT_MOTION, self.MenuPos)


    def makeMenuBar(self):

        fileMenu = wx.Menu()
        helloItem = fileMenu.Append(-1, "&Load Backround Image")
        fileMenu.AppendSeparator()
        exitItem = fileMenu.Append(wx.ID_EXIT)
        helpMenu = wx.Menu()
        aboutItem = helpMenu.Append(wx.ID_ABOUT)
        self.menuBar = wx.MenuBar()
        self.menuBar.Append(fileMenu, "&File")
        self.menuBar.Append(helpMenu, "&Help")

        # Give the menu bar to the frame
        self.SetMenuBar(self.menuBar)
        self.menuBar.Hide()
        # Finally, associate a handler function with the EVT_MENU event for
        # each of the menu items. That means that when that menu item is
        # activated then the associated handler function will be called.
        self.Bind(wx.EVT_MENU, self.OpenImage, helloItem)
        self.Bind(wx.EVT_MENU, self.OnExit,  exitItem)
        self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)

    def MenuPos(self, event):
        x, y = event.GetPosition()
        if y <= 2:
            self.menuBar.Show()
        if y >= 3:
            self.menuBar.Hide()
        event.Skip()

    def OnExit(self, event):
                self.Close(True)

    def OnAbout(self, event):
        wx.MessageBox("Test",
                      "About",
                      wx.OK|wx.ICON_INFORMATION)

    def OpenImage(self, event):
        with wx.FileDialog (None, "Choose image", wildcard="PNG files (*.png)|*.png", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return       # the user changed their mind
            else:
                # Gets rid of other images
                for i in self.images:
                    i.Destroy()
                    self.images.remove(i)

                # Displays image and adds image object to [self.images]
                ImageName = fileDialog.GetPath()
                png = wx.Image(ImageName, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
                self.images.append(wx.StaticBitmap(self, -1, png, (0, 0), (png.GetWidth(), png.GetHeight())))
                print(ImageName)


if __name__ == '__main__':
    app = wx.App()
    frm = HelloFrame(None, title='FileHeader Test')
    frm.Show()
    app.MainLoop()

enter image description hereenter image description here

...