Can't pass parameters to function from WxPython Menu Item - python

I'm having trouble getting sensible output when I try to bind menu buttons to a function. First, I pass a few items to create a menu in my application:
imported_applications = ["foo", "bar"]
application_menu = wx.Menu()
for app in imported_applications:
# Create Items
item = wx.MenuItem(application_menu, wx.ID_ANY, app, )
application_menu.Append(item)
# Bind to function
self.Bind(wx.EVT_MENU, self.select_application, item, id=app)
# Add to menubar
menubar.Append(application_menu, '&Applications')
self.SetMenuBar(menubar)
Then I try to get that parameter when select_application is called:
def select_application(self, event):
id_selected = event.GetId()
print(id_selected)
Outputs:
-2014
-2015
Not sure where that is coming from but I expect it to output the id that I set at bind. The contents of imported_applications are two strings, i.e. ["foo", "bar]

app = [ "foo", "bar", ]
for app in ...
Here, your app variable is overwritten.

You are not appending the items correctly.The wx.Menu requires other parameters to its Append method. You should be receiving an error if you run that code as-is. Instead, you'll want to use AppendItem. If you want the menu's label to be printed in the event handler, then you'll have to extraxt the id from the event and use that to acquire the label's text. Here is a demo that does just that:
import wx
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "wx.Menu Tutorial")
# Add a panel so it looks the correct on all platforms
self.panel = wx.Panel(self, wx.ID_ANY)
menuBar = wx.MenuBar()
fileMenu = wx.Menu()
imported_applications = ["foo", "bar"]
for item in imported_applications:
item = wx.MenuItem(fileMenu, wx.ID_ANY, item)
fileMenu.AppendItem(item)
self.Bind(wx.EVT_MENU, self.onMenuPress, item)
menuBar.Append(fileMenu, "&File")
self.SetMenuBar(menuBar)
#----------------------------------------------------------------------
def onMenuPress(self, event):
""""""
menu_id = event.GetId()
obj = event.GetEventObject()
menu_label = obj.GetLabelText(menu_id)
print menu_label
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()

Related

How to fix the layout stacking in wxpython

I'm trying to display the connection settings, that are required for an ssh connection, i'm using the wx.BoxSizer to arrange the layout, unfortunately the layout doesn't work and stacks all elements in the top left corner (Until i resize the window by scaling/maximizing).
I've already tried to use:self.Update(),self.Refresh() and self.Layout()
after i called self.Show(True) method but this doesn't work for me.
If i remove the section 'statusbar setup' and 'creating the menubar' it works but i need those.
import wx
import connectionSettingsProperties
import connectionSettings
from pubsub import pub
class MyFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self, parent, title = title, size = (1600,800))
panel = wx.Panel(self)
#statusbar setup
self.CreateStatusBar()
# menu setup
filemenu = wx.Menu()
# creating the menubar
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"Menu")
self.SetMenuBar(menuBar)
#connectionstatus init
self.ipLabel = wx.StaticText(panel, label = 'ip:')
self.usernameLabel = wx.StaticText(panel, label = 'username:')
#building layout
vboxMain = wx.BoxSizer(wx.VERTICAL)
hboxConnection = wx.BoxSizer(wx.HORIZONTAL)
hboxConnection.Add(self.ipLabel)
hboxConnection.Add(self.usernameLabel)
vboxMain.Add(hboxConnection)
panel.SetSizer(vboxMain)
#show content
self.Show(True)
app = wx.App(False)
frame = MyFrame(None, 'MyApp')
app.MainLoop()
this is what it's initially showing: https://imgur.com/VQebA9t
and this is how it's supposed to look like: https://imgur.com/60V1tcF
The second result is showing as soon as i rescale the window.
You are really close. You should only add the line:
vboxMain.Fit(panel)
below the line:
panel.SetSizer(vboxMain)

wxPython how do I retrieve information from a dialog box opened by a button

I'm trying to pull data from a text entry dialog box that's opened by a button click event using wxpython using this code.
import wx
class apple(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'PyLabs', size=(840,600))
panel = wx.Panel(self)
box = wx.TextEntryDialog(None, 'hi', 'hi', 'hi')
status_bar = self.CreateStatusBar()
menu_bar = wx.MenuBar()
options_menu = wx.Menu()
options_menu.Append(wx.NewId(), "Settings", "OpenSettings...")
options_menu.Append(wx.NewId(), "Advanced", "Check Advanced...")
menu_bar.Append(options_menu, "Options")
self.SetMenuBar(menu_bar)
New_Experiment_Button = wx.Button(panel, pos=(10,10), label='New Experiment', size=(120, 40))
answer = self.Bind(wx.EVT_BUTTON, self.openFrame, New_Experiment_Button)
print(answer)
def openFrame(self, event):
box = wx.TextEntryDialog(None, 'hi', 'hi', 'hi')
if box.ShowModal() == wx.ID_OK:
answer = str(box.getValue)
event.Skip()
return answer
if __name__=='__main__':
app=wx.PySimpleApp()
frame = apple(parent=None, id=-1)
frame.Show()
app.MainLoop()
I'm extremely new to wxpython coding and i don't understand how i'm to grab the data pulled by the button event when it's called from inside the Bind() function.
The output of print(answer) is "None"
If anybody could help me with this it'd be greatly appreciated!
Why not just have the print in the function, why would you need to return it to def __init__ ?
def openFrame(self, event):
box = wx.TextEntryDialog(None, 'hi', 'hi', 'hi')
if box.ShowModal() == wx.ID_OK:
answer = box.GetValue()
event.Skip()
print answer
The "answer" is box.GetValue(), however you have a few more issues with your experiment, see below, check the differences
Edited with reference to your comments, store you result in a self variable and see the difference in the Bind statements on the buttons.
import wx
class apple(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'PyLabs', size=(840,600))
panel = wx.Panel(self)
status_bar = self.CreateStatusBar()
menu_bar = wx.MenuBar()
options_menu = wx.Menu()
options_menu.Append(wx.NewId(), "Settings", "OpenSettings...")
options_menu.Append(wx.NewId(), "Advanced", "Check Advanced...")
menu_bar.Append(options_menu, "Options")
self.SetMenuBar(menu_bar)
New_Experiment_Button = wx.Button(panel, pos=(10,10), label='New Experiment', size=(130, 30))
New_Experiment_Button.Bind(wx.EVT_BUTTON, self.openFrame)
Result_Button = wx.Button(panel, pos=(10,60), label='Result of Experiment', size=(130, 30))
Result_Button.Bind(wx.EVT_BUTTON, self.resultValue)
self.Text = wx.TextCtrl(panel, -1, "Nothing yet", pos=(10,100), size=(200,30))
def openFrame(self, event):
box = wx.TextEntryDialog(None, 'What is your answer', 'Heading','Hi')
if box.ShowModal() == wx.ID_OK:
self.answer = box.GetValue()
box.Destroy()
def resultValue(self, event):
try:
self.Text.SetValue(self.answer)
except:
self.Text.SetValue("No answer yet supplied")
if __name__=='__main__':
app=wx.App()
frame = apple(parent=None, id=-1)
frame.Show()
app.MainLoop()

wxPython : Creating a soundboard with panels

I am making a quick and dirty soundboard using the wxPython package and was wondering how to go by implementing a scroll-list of sounds to play.
Here is a picture of what I am trying to convey:
http://i.imgur.com/av0E5jC.png
and here is my code so far:
import wx
class windowClass(wx.Frame):
def __init__(self, *args, **kwargs):
super(windowClass,self).__init__(*args,**kwargs)
self.basicGUI()
def basicGUI(self):
panel = wx.Panel(self)
menuBar = wx.MenuBar()
fileButton = wx.Menu()
editButton = wx.Menu()
exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...')
menuBar.Append(fileButton, 'File')
menuBar.Append(editButton, 'Edit')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.Quit, exitItem)
wx.TextCtrl(panel,pos=(10,10), size=(250,150))
self.SetTitle("Soundboard")
self.Show(True)
def Quit(self, e):
self.Close()
def main():
app = wx.App()
windowClass(None)
app.MainLoop()
main()
My question remains, how does one load a list of sounds on that panel and click a certain button to play that sound. I don't really care about implementing pause and fast forward features since this is only going to play really quick sound files.
Thanks in advance.
Just removed the text widget, replaced by a listbox, and hooked a callback on item click, slightly elaborate: when clicking, it finds the position of the item, retrieves the label name and fetches the filename in the dictionary
(we want to play a .wav file with a path, but not necessarily display the full filename)
I refactored the code so callbacks and other attributes are private, helps the lisibility.
import wx
class windowClass(wx.Frame):
def __init__(self, *args, **kwargs):
super(windowClass,self).__init__(*args,**kwargs)
self.__basicGUI()
def __basicGUI(self):
panel = wx.Panel(self)
menuBar = wx.MenuBar()
fileButton = wx.Menu()
editButton = wx.Menu()
exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...')
menuBar.Append(fileButton, 'File')
menuBar.Append(editButton, 'Edit')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.__quit, exitItem)
self.__sound_dict = { "a" : "a.wav","b" : "b.wav","c" : "c2.wav"}
self.__sound_list = sorted(self.__sound_dict.keys())
self.__list = wx.ListBox(panel,pos=(20,20), size=(250,150))
for i in self.__sound_list: self.__list.Append(i)
self.__list.Bind(wx.EVT_LISTBOX,self.__on_click)
#wx.TextCtrl(panel,pos=(10,10), size=(250,150))
self.SetTitle("Soundboard")
self.Show(True)
def __on_click(self,event):
event.Skip()
name = self.__sound_list[self.__list.GetSelection()]
filename = self.__sound_dict[name]
print("now playing %s" % filename)
def __quit(self, e):
self.Close()
def main():
app = wx.App()
windowClass(None)
app.MainLoop()
main()

wxPython and add Options Menu when select in Menu Bar

I have set up a wxpython GUI that has a menu bar and some items in the menu bar. What I would like to do is select an item in my menu bar (ex. File - Options), and when i select "Options" have a dialog box pop up in which I can set different parameters in my code. Similar behaviors would be wx.FontDialog and wx.FileDialog -- However, I want mine to be custom in that i could have radio buttons and check boxes as selectable options. How do I do this?
Snippets of my code are:
Here is where I set up part of the Main application and GUI (I have layout and box sizers set up in another section):
class TMainForm(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.Splitter = wx.SplitterWindow(self, -1, style=wx.SP_3D|wx.SP_BORDER)
self.PlotPanel = wx.Panel(self.Splitter, -1)
self.FilePanel = wx.Panel(self.Splitter, -1)
#self.SelectionPanel = wx.Panel(self.Splitter,-1)
self.Notebook = wx.Notebook(self.FilePanel, -1)#, style=0)
self.ReportPage = wx.Panel(self.Notebook, -1)
self.FilePage = wx.Panel(self.Notebook, -1)
Here is where I set up part of the Menu Bar:
self.MainMenu = wx.MenuBar()
self.FileMenu = wx.Menu()
self.OptimizeMenu = wx.Menu()
self.HelpMenu = wx.Menu()
self.OptimizeOptions= wx.MenuItem(self.OptimizeMenu, 302, "&Select Parameters","Select Parameters for Optimization",wx.ITEM_NORMAL)
self.OptimizeMenu.AppendItem(self.OptimizeOptions)
self.MainMenu.Append(self.OptimizeMenu, "&Optimization")
Here is where I bind an event to my "options" part of my menu bar. When I click on this, I want a pop up menu dialog to show up
self.Bind(wx.EVT_MENU, self.OnOptimizeOptions, self.OptimizeOptions)
This is the function in which i'm hoping the pop up menu will be defined. I would like to do it in this format if possible (rather than doing separate classes).
def OnOptimizeOptions(self,event):
give me a dialog box (radio buttons, check boxes, etc)
I have only shown snippets, but all of my code does work. My GUI and menu bars are set up correctly - i just don't know how to get a pop up menu like the wx.FileDialog and wx.FontDialog menus. Any help would be great! Thanks
You would want to instantiate a dialog in your handler (OnOptimizeOptions). Basically you would subclass wx.Dialog and put in whatever widgets you want. Then you'd instantiate it in your handler and call ShowModal. Something like this psuedo-code:
myDlg = MyDialog(*args)
myDlg.ShowModal()
See the Custom Dialog part on zetcodes site: http://zetcode.com/wxpython/dialogs/ (near the bottom) for one example.
EDIT - Here's an example:
import wx
########################################################################
class MyDialog(wx.Dialog):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Dialog.__init__(self, None, title="Options")
radio1 = wx.RadioButton( self, -1, " Radio1 ", style = wx.RB_GROUP )
radio2 = wx.RadioButton( self, -1, " Radio2 " )
radio3 = wx.RadioButton( self, -1, " Radio3 " )
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(radio1, 0, wx.ALL, 5)
sizer.Add(radio2, 0, wx.ALL, 5)
sizer.Add(radio3, 0, wx.ALL, 5)
for i in range(3):
chk = wx.CheckBox(self, label="Checkbox #%s" % (i+1))
sizer.Add(chk, 0, wx.ALL, 5)
self.SetSizer(sizer)
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "wx.Menu Tutorial")
# Add a panel so it looks the correct on all platforms
self.panel = wx.Panel(self, wx.ID_ANY)
menuBar = wx.MenuBar()
fileMenu = wx.Menu()
optionsItem = fileMenu.Append(wx.NewId(), "Options",
"Show an Options Dialog")
self.Bind(wx.EVT_MENU, self.onOptions, optionsItem)
exitMenuItem = fileMenu.Append(wx.NewId(), "Exit",
"Exit the application")
self.Bind(wx.EVT_MENU, self.onExit, exitMenuItem)
menuBar.Append(fileMenu, "&File")
self.SetMenuBar(menuBar)
#----------------------------------------------------------------------
def onExit(self, event):
""""""
self.Close()
#----------------------------------------------------------------------
def onOptions(self, event):
""""""
dlg = MyDialog()
dlg.ShowModal()
dlg.Destroy()
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()

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