how to add a window to a frame in wxpython - python

How to open the window inside a frame in wxpython.
I want to open a window on clicking File->SubFile .The code is given below.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
class MainMenu(wx.Frame):
def __init__(self, *args, **kwargs):
# ID_F = 1
super(MainMenu, self).__init__(*args, **kwargs)
self.Maximize(True)
self.InitUI()
def InitUI(self):
#self.Bind(wx.EVT_MENU, self.OnAbout, None,id= 1)
fileMenu1 = wx.Menu()
menubar = wx.MenuBar()
fitem1 = fileMenu1.Append(1, '&Sub File\tCtrl+B', 'Sub File..')
menubar.Append(fileMenu1, '&File')
self.SetMenuBar(menubar)
self.SetTitle('Simple menu')
self.Centre()
self.Show(True)
def OnAbout(self, event):
AboutFrame().Show()
class AboutFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent, 5, 'New Window', size=(400,300))
wx.Frame.CenterOnScreen(self)
def main():
ex = wx.App()
MainMenu(None)
ex.MainLoop()
if __name__ == '__main__':
main()
I thought it would be simple.
How to center the subwindow on the screen.
I'm incredibly new to this,

Note To respond to a menu selection, provide a handler for EVT_MENU
[for] the frame that contains the menu.
http://wxpython.org/Phoenix/docs/html/MenuBar.html#menubar
...
wx.Frame methods:
Center()
http://wxpython.org/Phoenix/docs/html/Frame.html?highlight=frame#Frame.Centre
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
class MainMenu(wx.Frame):
def __init__(self, *args, **kwargs):
super(MainMenu, self).__init__(*args, **kwargs)
self.Maximize(True)
self.InitUI()
def InitUI(self):
fileMenu1 = wx.Menu()
menubar = wx.MenuBar()
#********HERE************
fitem1 = fileMenu1.Append(-1, '&Sub File\tCtrl+B', 'Sub File..')
fitem2 = fileMenu1.Append(-1, '&Dog\tCtrl+D', 'Sub Dog..')
self.Bind(wx.EVT_MENU, self.onclick_subfile, fitem1)
#*************************
menubar.Append(fileMenu1, '&File')
self.SetMenuBar(menubar)
self.SetTitle('Simple menu')
self.Centre()
self.Show(True)
def OnAbout(self, event):
AboutFrame().Show()
#**********HERE*************
def onclick_subfile(self, event):
frame = wx.Frame(None, -1, "My Second Frame")
frame.Center()
frame.Show()
class AboutFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent, 5, 'New Window', size=(400,300))
wx.Frame.CenterOnScreen(self)
def main():
ex = wx.App(redirect=False)
MainMenu(None)
ex.MainLoop()
if __name__ == '__main__':
main()
If you want the inner window to be destroyed when you close the outer window, then make the outer window the parent of the inner window:
def onclick_subfile(self, event):
frame = wx.Frame(self, -1, "My Second Frame")

Related

wxpython open second frame on mouse click no responding

env:python37,windows,wxpython
There's a main frame keep opening while app is running, now I'm trying to create a new frame on mouse right click, the new frame works good if I open it by button click, but if it is triggered by a mouse click event, it will hang and no responding. I'm thinking if there's something wrong with mouse listener, really appreciate if you have any idea.
here's the code detail:
import wx
import time
import win32api
from threading import Thread
class OtherFrame(wx.Frame):
"""
Class used for creating frames other than the main one
"""
def __init__(self, title, parent=None):
wx.Frame.__init__(self, parent=parent, title=title)
panel = wx.Panel(self)
panel.SetBackgroundColour('yellow')
self.Show()
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
btn = wx.Button(self, label='Create New Frame')
btn.Bind(wx.EVT_BUTTON, self.on_new_frame)
self.frame_number = 1
thread = Thread(target=self.monitorMouse, name='monitorMouse')
thread.daemon = True
thread.start()
def monitorMouse(self):
state_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128
state_right = win32api.GetKeyState(0x02) # Right button down = 0 or 1. Button up = -127 or -128
while True:
a = win32api.GetKeyState(0x01)
b = win32api.GetKeyState(0x02)
if b != state_right: # Button state changed
state_right = b
if b < 0:
print('Right Button Pressed')
else:
print('Right Button Released')
self.on_new_frame(None)
time.sleep(0.001)
def on_new_frame(self, event):
title = 'SubFrame {}'.format(self.frame_number)
frame = OtherFrame(title=title)
self.frame_number += 1
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Main Frame', size=(800, 600))
panel = MyPanel(self)
self.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MainFrame()
app.MainLoop()
If are determined to monitor the mouse using a thread, then I think that you are going to have to look at wx.lib.newevent.NewEvent().
From within the thread you would use wx.PostEvent to send the mouse event back to the main program.
However, wxpython already has the mouse events available to you, to which you can bind directly e.g.
import wx
class OtherFrame(wx.Frame):
def __init__(self, title, parent=None):
wx.Frame.__init__(self, parent=parent, title=title)
panel = wx.Panel(self)
panel.SetBackgroundColour('yellow')
self.Show()
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
btn = wx.Button(self, label='Create New Frame')
btn.Bind(wx.EVT_BUTTON, self.on_new_frame)
self.Bind(wx.EVT_LEFT_DOWN, self.Left)
self.Bind(wx.EVT_RIGHT_DOWN, self.Right)
self.Bind(wx.EVT_RIGHT_DCLICK, self.on_new_frame)
self.Bind(wx.EVT_CLOSE, self.Quit)
self.frame_number = 1
def Quit(self, event):
self.Destroy()
def Left(self, event):
print("Left Button")
event.Skip()
def Right(self, event):
print("Right Button")
def on_new_frame(self, event):
title = 'SubFrame {}'.format(self.frame_number)
frame = OtherFrame(parent=self,title=title)
self.frame_number += 1
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Main Frame', size=(800, 600))
panel = MyPanel(self)
self.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MainFrame()
app.MainLoop()
As an aside, note the line
frame = OtherFrame(parent=self,title=title)
sending the parent allows all outstanding OtherFrame's to close when the main frame is closed.

wxpython phoenix says that Frame init args are wrong

I am trying to create simple window with menu in wx python 3.0.4.
Actually I get an error:
wx.Frame.init(self, ID_ANY, "Title", DefaultPosition, (350,200), DEFAULT_FRAME_STYLE, FrameNameStr) TypeError: Frame():
arguments did not match any overloaded call: overload 1: too many
arguments overload 2: argument 1 has unexpected type 'StandardID'
Even this code is from documentation. Could someone tell me what am I doing wrong, please?
import wx
from wx import *
class MainWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, ID_ANY, "Title", DefaultPosition, (350,200), DEFAULT_FRAME_STYLE, FrameNameStr)
self.Bind(wx.EVT_CLOSE, self.OnClose)
menuBar = wx.MenuBar()
menu = wx.Menu()
m_exit = menu.Append(wx.ID_EXIT, "E&xit", "Close window and exit program.")
self.Bind(wx.EVT_MENU, self.OnClose, m_exit)
menuBar.Append(menu, "&File")
menu = wx.Menu()
m_about = menu.Append(wx.ID_ABOUT, "&About", "Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, m_about)
menuBar.Append(menu, "&Help")
self.SetMenuBar(menuBar)
self.main_panel = MainPanel(self)
def OnClose(self, e):
self.Close()
def OnAbout(self, event):
dlg = AboutBox(self)
dlg.ShowModal()
dlg.Destroy()
class MainPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
class AboutBox(wx.MessageDialog):
def __init__(self, parent):
wx.MessageDialog.__init__(parent, "About", "About", wx.OK | wx.ICON_INFORMATION, pos=DefaultPosition)
self.CentreOnParent(wx.BOTH)
self.SetFocus()
if __name__ == "__main__":
app = wx.App(False)
frame = MainWindow()
frame.Show()
app.MainLoop()
Frame(parent, id=ID_ANY, title="", pos=DefaultPosition,
size=DefaultSize, style=DEFAULT_FRAME_STYLE, name=FrameNameStr)
You missed the parent argument.
Working code
import wx
class MainWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(
self, None, wx.ID_ANY, "Title", wx.DefaultPosition, (350,200),
wx.DEFAULT_FRAME_STYLE, wx.FrameNameStr)
self.Bind(wx.EVT_CLOSE, self.OnClose)
menuBar = wx.MenuBar()
menu = wx.Menu()
m_exit = menu.Append(
wx.ID_EXIT, "E&xit", "Close window and exit program.")
self.Bind(wx.EVT_MENU, self.OnClose, m_exit)
menuBar.Append(menu, "&File")
menu = wx.Menu()
m_about = menu.Append(
wx.ID_ABOUT, "&About", "Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, m_about)
menuBar.Append(menu, "&Help")
self.SetMenuBar(menuBar)
self.main_panel = MainPanel(self)
def OnClose(self, e):
self.Destroy()
def OnAbout(self, event):
dlg = AboutBox(self)
dlg.ShowModal()
dlg.Destroy()
class MainPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
class AboutBox(wx.MessageDialog):
def __init__(self, parent):
wx.MessageDialog.__init__(
self, parent, "About", "About", wx.OK | wx.ICON_INFORMATION,
pos=wx.DefaultPosition)
self.CentreOnParent(wx.BOTH)
if __name__ == "__main__":
app = wx.App(False)
frame = MainWindow()
frame.Show()
app.MainLoop()

wx python windows can't hide my MenuBar

Yop, all is in title, i wanna Hide my wx.MenuBar() on my soft, and that is works well on my Ubuntu, but when i switch my soft on Windows, my wx.MenuBar() is not hide... Any Ideas?
menuBar = wx.MenuBar()
self.fileMenu = wx.Menu()
i = self.fileMenu.Append(-1, _("Load Model\tCTRL+L"))
self.Bind(wx.EVT_MENU, self.showLoadModel(), i)
menuBar.Append(self.fileMenu, 'File')
self.SetMenuBar(menuBar)
menuBar.Hide()
EDIT: Then how can i catch a CTRL+L without EVT_MENU ?
It's ok i found it:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
class Example(wx.Frame):
def __init__(self, *args, **kw):
super(Example, self).__init__(*args, **kw)
self.InitUI()
def InitUI(self):
pnl = wx.Panel(self)
pnl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
pnl.SetFocus()
self.SetSize((250, 180))
self.SetTitle('Key event')
self.Centre()
self.Show(True)
def OnKeyDown(self, e):
key = e.GetKeyCode()
if key == wx.WXK_ESCAPE:
ret = wx.MessageBox('Are you sure to quit?', 'Question',
wx.YES_NO | wx.NO_DEFAULT, self)
if ret == wx.YES:
self.Close()
def main():
ex = wx.App()
Example(None)
ex.MainLoop()

how to hide wxpython status bar by default

I am learning wxpython following the tutorials on zetcode about menu bars and status bars. Please forgive me if the question is stupid.
The code below from the website works fine, but I am curious how to hide the status bar by default (when the application window popup).
import wx
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
menubar = wx.MenuBar()
fileMenu = wx.Menu()
viewMenu = wx.Menu()
self.shst = viewMenu.Append(wx.ID_ANY, 'Show statubar',
'Show Statusbar', kind=wx.ITEM_CHECK)
self.shtl = viewMenu.Append(wx.ID_ANY, 'Show toolbar',
'Show Toolbar', kind=wx.ITEM_CHECK)
viewMenu.Check(self.shst.GetId(), True)
viewMenu.Check(self.shtl.GetId(), True)
self.Bind(wx.EVT_MENU, self.ToggleStatusBar, self.shst)
self.Bind(wx.EVT_MENU, self.ToggleToolBar, self.shtl)
menubar.Append(fileMenu, '&File')
menubar.Append(viewMenu, '&View')
self.SetMenuBar(menubar)
self.toolbar = self.CreateToolBar()
self.toolbar.AddLabelTool(1, '', wx.Bitmap('texit.png'))
self.toolbar.Realize()
self.statusbar = self.CreateStatusBar()
self.statusbar.SetStatusText('Ready')
self.SetSize((350, 250))
self.SetTitle('Check menu item')
self.Centre()
self.Show(True)
def ToggleStatusBar(self, e):
if self.shst.IsChecked():
self.statusbar.Show()
else:
self.statusbar.Hide()
def ToggleToolBar(self, e):
if self.shtl.IsChecked():
self.toolbar.Show()
else:
self.toolbar.Hide()
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
I have tried to change one line above into:
viewMenu.Check(self.shst.GetId(), False)
Sadly, that didn't work out.
Willing to hear any advice! Thanks in advance!
Specs: wxpython: 2.8.12.1; python 2.7; Ubuntu 12.04
IMHO, because viewMenu.Check(..) is called before UI initialization is done (before event loop begin), it may not fire event.
How about manually call ToggleStatusBar method after viewMenu.Check?
def InitUI(self):
....
viewMenu.Check(self.shst.GetId(), False)
self.ToggleStatusBar(None)
This might be what you mean by Just curious if any built-in functions can do that kind of "update" job?
There is a wx.EVT_UPDATE_UI event, i've modifed your code to use it.
UpdateUIEvent
import wx
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
menubar = wx.MenuBar()
fileMenu = wx.Menu()
viewMenu = wx.Menu()
self.shst = viewMenu.Append(-1, 'Show statubar', 'Show Statusbar',
kind=wx.ITEM_CHECK)
self.shtl = viewMenu.Append(-1, 'Show toolbar', 'Show Toolbar',
kind=wx.ITEM_CHECK)
self.shst.Check(False)
self.shtl.Check(True)
menubar.Append(fileMenu, '&File')
menubar.Append(viewMenu, '&View')
self.SetMenuBar(menubar)
self.toolbar = self.CreateToolBar()
self.toolbar.AddLabelTool(1, '', wx.EmptyBitmap(16, 16))
self.toolbar.Realize()
self.statusbar = self.CreateStatusBar()
self.statusbar.SetStatusText('Ready')
self.Bind(wx.EVT_UPDATE_UI, self.on_update_status_bar, self.statusbar)
self.Bind(wx.EVT_UPDATE_UI, self.on_update_tool_bar, self.toolbar)
self.SetSize((350, 250))
self.SetTitle('Check menu item')
self.Centre()
self.Show(True)
def on_update_status_bar(self, event):
event.Show(self.shst.IsChecked())
def on_update_tool_bar(self, event):
event.Show(self.shtl.IsChecked())
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
I think this way would be better.
statusBarHandle.Hide()
self.SetStatusBar(None) #Disable Status Bar
#Enable
statusBarHandle.Show()
self.SetStatusBar(statusBarHandle) #Back created StatusBar(self.CreateStatusBar function)
#Useful tip: for update all widgets in AUI, use AUI function Update()
#For sizers you need to use the Layout() or Update() function

wxpython auinotebook close tab event

What event is used when I close a tab in an auinotebook? I tested with
EVT_AUINOTEBOOK_PAGE_CLOSE(D). It didn't work.
I would also like to fire a right click on the tab itself event.
Where can I find all the events that can be used with the aui manager/notebook? Might just be my poor searching skills, but I can't find any lists over the different events that exist, not for mouse/window events either. It would be really handy to have a complete list.
#!/usr/bin/python
#12_aui_notebook1.py
import wx
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.nb = wx.aui.AuiNotebook(self)
self.new_panel('Page 1')
self.new_panel('Page 2')
self.new_panel('Page 3')
self.nb.Bind(wx.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close)
def new_panel(self, nm):
pnl = wx.Panel(self)
pnl.identifierTag = nm
self.nb.AddPage(pnl, nm)
self.sizer = wx.BoxSizer()
self.sizer.Add(self.nb, 1, wx.EXPAND)
self.SetSizer(self.sizer)
def close(self, event):
print 'closed'
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, '12_aui_notebook1.py')
frame.Show()
self.SetTopWindow(frame)
return 1
if __name__ == "__main__":
app = MyApp(0)
# wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
Oerjan Pettersen
This is the bind command you want:
self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close, self.nb)
To detect a right click on the tab (e.g. to show a custom context menu):
self.Bind(wx.aui.EVT_AUINOTEBOOK_TAB_RIGHT_DOWN, self.right, self.nb)
Here's a list of the aui notebook events:
EVT_AUINOTEBOOK_PAGE_CLOSE
EVT_AUINOTEBOOK_PAGE_CLOSED
EVT_AUINOTEBOOK_PAGE_CHANGED
EVT_AUINOTEBOOK_PAGE_CHANGING
EVT_AUINOTEBOOK_BUTTON
EVT_AUINOTEBOOK_BEGIN_DRAG
EVT_AUINOTEBOOK_END_DRAG
EVT_AUINOTEBOOK_DRAG_MOTION
EVT_AUINOTEBOOK_ALLOW_DND
EVT_AUINOTEBOOK_DRAG_DONE
EVT_AUINOTEBOOK_BG_DCLICK
EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN
EVT_AUINOTEBOOK_TAB_MIDDLE_UP
EVT_AUINOTEBOOK_TAB_RIGHT_DOWN
EVT_AUINOTEBOOK_TAB_RIGHT_UP
From: {python folder}/Lib/site-packages/{wxpython folder}/wx/aui.py

Categories

Resources