Python: Right click on objectlistview not showing item name selected - python

I have been working with example stated under http://wiki.wxpython.org/PopupMenuOnRightClick .
The output expected when right clicking on an item would be Perform <action> on <item selected> . However the output I get is Perform <action> on "."
The code I used to test the example is:
import wx
import sys
sys.path.append("..")
from ObjectListView import ObjectListView, ColumnDefn
### 2. Launcher creates wxMenu. ###
menu_titles = [ "Open",
"Properties",
"Rename",
"Delete" ]
menu_title_by_id = {}
for title in menu_titles:
menu_title_by_id[ wx.wx.NewId() ] = title
class Track(object):
"""
Simple minded object that represents a song in a music library
"""
def __init__(self, title, artist, album):
self.title = title
self.artist = artist
self.album = album
def GetTracks():
"""
Return a collection of tracks
"""
return [
Track("Sweet Lullaby", "Deep Forest", "Deep Forest"),
Track("Losing My Religion", "U2", "Out of Time"),
Track("En el Pais de la Libertad", "Leon Gieco", "Leon Gieco"),
]
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.Init()
def Init(self):
self.InitModel()
self.InitWidgets()
self.InitObjectListView()
def InitModel(self):
self.songs = GetTracks()
def InitWidgets(self):
panel = wx.Panel(self, -1)
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(panel, 1, wx.ALL|wx.EXPAND)
self.SetSizer(sizer_1)
self.myOlv = ObjectListView(panel, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_2.Add(self.myOlv, 1, wx.ALL|wx.EXPAND, 4)
panel.SetSizer(sizer_2)
self.Layout()
def InitObjectListView(self):
self.myOlv.SetColumns([
ColumnDefn("Title", "left", 120, "title"),
ColumnDefn("Artist", "left", 100, "artist"),
ColumnDefn("Album", "left", 100, "album")
])
self.myOlv.SetObjects(self.songs)
self.myOlv.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.RightClick)
def RightClick(self,event):
# record what was clicked
self.list_item_clicked = right_click_context = event.GetString()
menu = wx.wx.Menu()
menu.Bind(wx.EVT_MENU, self.MenuSelectionCb)
for (id,title) in menu_title_by_id.items():
### 3. Launcher packs menu with Append. ###
menu.Append( id, title )
### 5. Launcher displays menu with call to PopupMenu, invoked on the source component, passing event's GetPoint. ###
#self.frame.PopupMenu( menu, event.GetPoint() )
frame_1.PopupMenu(menu, event.GetPoint() )
menu.Destroy() # destroy to avoid mem leak
def MenuSelectionCb( self, event ):
# do something
operation = menu_title_by_id[ event.GetId() ]
target = self.list_item_clicked
print 'Perform "%(operation)s" on "%(target)s."' % vars()
class MyPopupMenu(wx.Menu):
def __init__(self, parent):
super(MyPopupMenu, self).__init__()
self.parent = parent
mmi = wx.MenuItem(self, wx.NewId(), 'Minimize')
self.AppendItem(mmi)
self.Bind(wx.EVT_MENU, self.OnMinimize, mmi)
cmi = wx.MenuItem(self, wx.NewId(), 'Close')
self.AppendItem(cmi)
self.Bind(wx.EVT_MENU, self.OnClose, cmi)
def OnMinimize(self, e):
self.parent.Iconize()
def OnClose(self, e):
self.parent.Close()
if __name__ == '__main__':
app = wx.PySimpleApp(1)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "ObjectListView Track Test")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
So, how to ensure to get the corresponding item name when right clicking and selecting an action for that item?
Notes:
I am using wxpython 2.7.2.0 and tested it under Python 2.5 and Python 2.7
This has been asked already under python: Right Click on list menu not showing item selected . However the solution provided (to change GetText to GetString) hadn't the expected results.

To get the selected object inside of the RightClick event handler you can use objectlistviews GetSelectedObject() method, the code below is modified to use this method and then display the selected objects title.
I don't think you will get the selected object from the event wx.EVT_LIST_ITEM_RIGHT_CLICK as it is not a objectlistview specific event, its a plain listview event.
import wx
import sys
sys.path.append("..")
from ObjectListView import ObjectListView, ColumnDefn
### 2. Launcher creates wxMenu. ###
menu_titles = [ "Open",
"Properties",
"Rename",
"Delete" ]
menu_title_by_id = {}
for title in menu_titles:
menu_title_by_id[ wx.NewId() ] = title
class Track(object):
"""
Simple minded object that represents a song in a music library
"""
def __init__(self, title, artist, album):
self.title = title
self.artist = artist
self.album = album
def GetTracks():
"""
Return a collection of tracks
"""
return [
Track("Sweet Lullaby", "Deep Forest", "Deep Forest"),
Track("Losing My Religion", "U2", "Out of Time"),
Track("En el Pais de la Libertad", "Leon Gieco", "Leon Gieco"),
]
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.Init()
def Init(self):
self.InitModel()
self.InitWidgets()
self.InitObjectListView()
def InitModel(self):
self.songs = GetTracks()
def InitWidgets(self):
panel = wx.Panel(self, -1)
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(panel, 1, wx.ALL | wx.EXPAND)
self.SetSizer(sizer_1)
self.myOlv = ObjectListView(panel, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_2.Add(self.myOlv, 1, wx.ALL | wx.EXPAND, 4)
panel.SetSizer(sizer_2)
self.Layout()
def InitObjectListView(self):
self.myOlv.SetColumns([
ColumnDefn("Title", "left", 120, "title"),
ColumnDefn("Artist", "left", 100, "artist"),
ColumnDefn("Album", "left", 100, "album")
])
self.myOlv.SetObjects(self.songs)
self.myOlv.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.RightClick)
def RightClick(self, event):
# record what was clicked
self.list_item_clicked = self.myOlv.GetSelectedObject()
menu = wx.Menu()
menu.Bind(wx.EVT_MENU, self.MenuSelectionCb)
for (id_, title) in menu_title_by_id.items():
### 3. Launcher packs menu with Append. ###
menu.Append(id_, title)
### 5. Launcher displays menu with call to PopupMenu, invoked on the source component, passing event's GetPoint. ###
# self.frame.PopupMenu( menu, event.GetPoint() )
frame_1.PopupMenu(menu, event.GetPoint())
menu.Destroy() # destroy to avoid mem leak
def MenuSelectionCb(self, event):
# do something
operation = menu_title_by_id[ event.GetId() ]
target = self.list_item_clicked.title
print 'Perform "%(operation)s" on "%(target)s."' % vars()
class MyPopupMenu(wx.Menu):
def __init__(self, parent):
super(MyPopupMenu, self).__init__()
self.parent = parent
mmi = wx.MenuItem(self, wx.NewId(), 'Minimize')
self.AppendItem(mmi)
self.Bind(wx.EVT_MENU, self.OnMinimize, mmi)
cmi = wx.MenuItem(self, wx.NewId(), 'Close')
self.AppendItem(cmi)
self.Bind(wx.EVT_MENU, self.OnClose, cmi)
def OnMinimize(self, e):
self.parent.Iconize()
def OnClose(self, e):
self.parent.Close()
if __name__ == '__main__':
app = wx.App(True)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "ObjectListView Track Test")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()

Related

Start a hidden panel with wxpython

I want to start an app with several panels hidden from the user and show them per request when interacting with the menu.
So far the `budget_panel' that I want to be initially hidden is always on display.
My code is as follows (likely it can be dramatically improved as it is my first time using wxwidgets and OOP in Python).
#!/usr/bin/python3
import sqlite3
import wx
class DB():
def __init__(self):
self.db = sqlite3.connect(':memory:')
self.cursor = self.db.cursor()
self.cursor.execute('CREATE TABLE invoices (id INT PRIMARY KEY, client TEXT)')
self.cursor.execute('INSERT INTO invoices (client) VALUES ("Empresa A")')
self.db.commit()
def myget(self, id):
return self.cursor.execute('SELECT * FROM {}'.format(id)).fetchall()
class BudgetPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(sizer)
self.choices = ["Empresa A", "Empresa B"]
self.choice = wx.Choice(parent, id=wx.ID_ANY, choices = self.choices)
sizer.Add(self.choice)
class EmptyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent = parent)
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
text = wx.StaticText(self, -1, 'Text', style = wx.ALIGN_CENTER | wx.TE_READONLY)
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
"Empresa",
size=(800,600))
self.db = DB()
self.menu()
self.empty_panel = EmptyPanel(self)
self.budget_panel = BudgetPanel(self)
self.panels = {1000 : self.empty_panel, 2001 : self.budget_panel}
for key in self.panels.keys():
if key == 1000:
self.panels[key].Show()
else:
self.panels[key].Hide()
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.empty_panel, 1, wx.EXPAND)
self.sizer.Add(self.budget_panel, 1, wx.EXPAND)
self.SetSizer(self.sizer)
def menu(self):
menubar = wx.MenuBar()
main_menu = wx.Menu()
budget_menu = main_menu.Append(2001, 'Presupuestos')
self.Bind(wx.EVT_MENU, self.change_panel, budget_menu)
menubar.Append(main_menu, '&GestiĆ³n')
self.SetMenuBar(menubar)
def change_panel(self, event):
for key in self.panels.keys():
if event.GetId() == key:
self.panels[key].Show()
else:
self.panels[key].Hide()
self.Layout()
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
'''

wx.Frame error when calling one script from another

The following is a bit of copied code from another question, it works fine as a standalone app, but the pop-up right-click menu references frame_1 which is not available if "if name == 'main':" is false, as it is when the program is called by another. What should this reference be changed to?
Thanks.
import wx
import sys
sys.path.append("..")
from ObjectListView import ObjectListView, ColumnDefn
### 2. Launcher creates wxMenu. ###
menu_titles = [ "Open",
"Properties",
"Rename",
"Delete" ]
menu_title_by_id = {}
for title in menu_titles:
menu_title_by_id[ wx.NewId() ] = title
class Track(object):
"""
Simple minded object that represents a song in a music library
"""
def __init__(self, title, artist, album):
self.title = title
self.artist = artist
self.album = album
def GetTracks():
"""
Return a collection of tracks
"""
return [
Track("Sweet Lullaby", "Deep Forest", "Deep Forest"),
Track("Losing My Religion", "U2", "Out of Time"),
Track("En el Pais de la Libertad", "Leon Gieco", "Leon Gieco"),
]
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.Init()
def Init(self):
self.InitModel()
self.InitWidgets()
self.InitObjectListView()
def InitModel(self):
self.songs = GetTracks()
def InitWidgets(self):
panel = wx.Panel(self, -1)
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(panel, 1, wx.ALL | wx.EXPAND)
self.SetSizer(sizer_1)
self.myOlv = ObjectListView(panel, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_2.Add(self.myOlv, 1, wx.ALL | wx.EXPAND, 4)
panel.SetSizer(sizer_2)
self.Layout()
def InitObjectListView(self):
self.myOlv.SetColumns([
ColumnDefn("Title", "left", 120, "title"),
ColumnDefn("Artist", "left", 100, "artist"),
ColumnDefn("Album", "left", 100, "album")
])
self.myOlv.SetObjects(self.songs)
self.myOlv.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.RightClick)
def RightClick(self, event):
# record what was clicked
self.list_item_clicked = self.myOlv.GetSelectedObject()
menu = wx.Menu()
menu.Bind(wx.EVT_MENU, self.MenuSelectionCb)
for (id_, title) in menu_title_by_id.items():
### 3. Launcher packs menu with Append. ###
menu.Append(id_, title)
### 5. Launcher displays menu with call to PopupMenu, invoked on the source component, passing event's GetPoint. ###
# self.frame.PopupMenu( menu, event.GetPoint() )
frame_1.PopupMenu(menu, event.GetPoint())
menu.Destroy() # destroy to avoid mem leak
def MenuSelectionCb(self, event):
# do something
operation = menu_title_by_id[ event.GetId() ]
target = self.list_item_clicked.title
print 'Perform "%(operation)s" on "%(target)s."' % vars()
class MyPopupMenu(wx.Menu):
def __init__(self, parent):
super(MyPopupMenu, self).__init__()
self.parent = parent
mmi = wx.MenuItem(self, wx.NewId(), 'Minimize')
self.AppendItem(mmi)
self.Bind(wx.EVT_MENU, self.OnMinimize, mmi)
cmi = wx.MenuItem(self, wx.NewId(), 'Close')
self.AppendItem(cmi)
self.Bind(wx.EVT_MENU, self.OnClose, cmi)
def OnMinimize(self, e):
self.parent.Iconize()
def OnClose(self, e):
self.parent.Close()
if __name__ == '__main__':
app = wx.App(True)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "ObjectListView Track Test")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
If you are going to import your code into another module, then you will just need to instantiate that frame in your new main application's code. Let's save your code as olv_tracks.py. Now import it like I do in the following code:
import wx
import olv_tracks
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Main App')
panel = wx.Panel(self)
self.Show()
# show other frame
frame = olv_tracks.MyFrame(None, -1, "ObjectListView Track Test")
frame.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
Now you just instantiate the frame the same way you did in your code.
Also, you need to change the reference to frame_1 in your RightClick method to self. So instead of frame_1.PopupMenu(menu, event.GetPoint()), it should be self.PopupMenu(menu, event.GetPoint())

On button click open wxpython TextEntryDialog and get multiple input from user

I want to open a TextEntryDialog, when user clicks the button. So if i have a button in the parent frame which i am going to bind this way:
self.Bind(wx.EVT_BUTTON, self.OnAddNew, self.add_new_btn)
Now i have to open a TextEntryDialog when user clicks the button add_new. I want to make textentrydialog somewthing like this
Python, Using wxPython to get multiple input from user
How can i do that? Do i need to just paste that code in ` def OnAddNew(self, event):
Here is the pastebin link to my code: https://pastebin.com/UEYscgFa
I have created class inside a function, so is it possible to do in that way?
NO!
GetData is a class in its own right.
That code already provides you with the method.
The MyFrame is all fluff, to create a standalone working example.
def OnButton(self,event):
dlg = GetData(parent = self.panel)
dlg.ShowModal()
if dlg.result_name:
self.log.AppendText("Name: "+dlg.result_name+"\n")
self.log.AppendText("Surname: "+dlg.result_surname+"\n")
self.log.AppendText("Nickname: "+dlg.result_nickname+"\n")
else:
self.log.AppendText("No Input found\n")
dlg.Destroy()
Edit: I don't understand where the instructions in my comments eluded you but for my sins, here is your code cleaned up and edited as in the comments.
import sqlite3
import wx
import os
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title, size=(1000,800))
self.inter_list = list()
self.plot_list = list()
self.InitUI()
self.Layout()
self.Centre()
self.Show()
def InitUI(self):
self.p = wx.Panel(self)
bs = wx.BoxSizer(wx.VERTICAL)
gs = wx.GridSizer(10, 18, 5, 5)
bs.Add(gs, 1, wx.EXPAND)
self.search_btn=wx.Button(self.p,-1,"Search!")
self.search_btn.Bind(wx.EVT_BUTTON, self.OnSearch, self.search_btn)
bs.Add(self.search_btn,0,wx.ALIGN_CENTER)
self.p.SetSizer(bs)
def OnSearch(self, event):
dlg = GetData(parent = self.p)
dlg.ShowModal()
if dlg.result_name:
print "Name: "+dlg.result_name+"\n"
print "Surname: "+dlg.result_surname+"\n"
print "Nickname: "+dlg.result_nickname+"\n"
else:
print "No Input found\n"
dlg.Destroy()
class GetData(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, wx.ID_ANY, "Name Input", size= (650,220))
self.p = wx.Panel(self,wx.ID_ANY)
self.lblname = wx.StaticText(self.p, label="Name", pos=(20,20))
self.name = wx.TextCtrl(self.p, value="", pos=(110,20), size=(500,-1))
self.lblsur = wx.StaticText(self.p, label="Surname", pos=(20,60))
self.surname = wx.TextCtrl(self.p, value="", pos=(110,60), size=(500,-1))
self.lblnick = wx.StaticText(self.p, label="Nickname", pos=(20,100))
self.nickname = wx.TextCtrl(self.p, value="", pos=(110,100), size=(500,-1))
self.saveButton =wx.Button(self.p, label="Save", pos=(110,160))
self.closeButton =wx.Button(self.p, label="Cancel", pos=(210,160))
self.saveButton.Bind(wx.EVT_BUTTON, self.SaveConnString)
self.closeButton.Bind(wx.EVT_BUTTON, self.OnQuit)
self.Bind(wx.EVT_CLOSE, self.OnQuit)
self.Show()
def OnQuit(self, event):
self.result_name = None
self.Destroy()
def SaveConnString(self, event):
self.result_name = self.name.GetValue()
self.result_surname = self.surname.GetValue()
self.result_nickname = self.nickname.GetValue()
self.Destroy()
app = wx.App()
Example(None, title = 'Raman Spectroscopy Database')
app.MainLoop()

Custom event listeners for wxpython widgets

as in the title, is it possible to add a custom event listener for wx widget and if so, how? More particularly I am trying to add one which listens to the changes of SelStart and SelEnd attributes of wx.Slider.
Thanks!
Below is the code for custom listener for wx.slider, I am calling it inside other listener's handler.
You can call this customize listener from the point where SelStart and SelEnd changing.
import wx
import wx.lib.newevent
DialogRespondEvent, EVT_DIALOG_RESPOND_EVENT = wx.lib.newevent.NewEvent()
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title = title,size = (250,150))
self.InitUI()
def InitUI(self):
pnl = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
self.Bind(EVT_DIALOG_RESPOND_EVENT, self.testing)
self.sld = wx.Slider(pnl, value = 10, minValue = 1, maxValue = 100,
style = wx.SL_HORIZONTAL|wx.SL_LABELS)
vbox.Add(self.sld,1,flag = wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, border = 20)
self.sld.Bind(wx.EVT_SLIDER, self.OnSliderScroll)
self.txt = wx.StaticText(pnl, label = 'Hello',style = wx.ALIGN_CENTER)
vbox.Add(self.txt,1,wx.ALIGN_CENTRE_HORIZONTAL)
pnl.SetSizer(vbox)
self.Centre()
self.Show(True)
def testing(self,evt):
print "you can do whatever you want here"
def OnSliderScroll(self, e):
obj = e.GetEventObject()
val = obj.GetValue()
font = self.GetFont()
font.SetPointSize(self.sld.GetValue())
self.txt.SetFont(font)
evt = DialogRespondEvent()
wx.PostEvent(self, evt)
ex = wx.App()
Mywin(None,'Slider demo')
ex.MainLoop()

Continuously check for radio button status [WxPython]

I have a listbox with a set of strings. The set of strings I want to display depends on which radio button is selected. I would like it such that while the user is interacting with the Form, if they ever change the radio button it will update the list box.
Here is my code (I'm leaving the array for t87 and t89 out because they are very long (assume they exist):
def OnBtnSuperTesting(self, event):
class MainWindow(wx.Frame):
def __init__(self, parent, title):
self.dirname=''
wx.Frame.__init__(self, parent, title=title, size=(320,440))
self.SetBackgroundColour(wx.WHITE)
self.CenterOnScreen()
self.CreateStatusBar()
self.radioT89 = wx.RadioButton(self, -1, 'T89 only', pos = (2,0), style = wx.RB_GROUP)
self.radioT87 = wx.RadioButton(self, -1, 'T87 only', pos = (154, 0))
self.radioKeySort = wx.RadioButton(self, -1, 'Sort by Key', pos = (2,40), style = wx.RB_GROUP)
self.radioAtoZ = wx.RadioButton(self, -1, 'Sort Name A-Z', pos = (2,60))
self.radioZtoA = wx.RadioButton(self, -1, 'Sort Name Z-A', pos = (2,80))
self.checkCode = wx.CheckBox(self, -1, 'Generate Code', pos = (154,40))
self.checkBuild = wx.CheckBox(self, -1, 'Generate Build Report', pos = (154, 60))
self.ln = wx.StaticLine(self, -1, pos = (0,15), size = (300,3), style = wx.LI_HORIZONTAL)
self.ln2 = wx.StaticLine(self, -1, pos = (150,15), size = (3,100), style = wx.LI_VERTICAL)
self.radioT87.Bind(wx.EVT_RADIOBUTTON, self.updateList)
#self.Bind(wx.EVT_RADIOBUTTON, self.radioT89, self.updateList())
self.listbox = wx.ListBox(self, -1, pos = (0,120), size = (300,200), choices = T89, style = (wx.LB_SINGLE|wx.LB_HSCROLL))
self.go = wx.Button(self,-1, label = 'Go!', pos = (110, 325))
# Setting up the menu.
filemenu= wx.Menu()
menuAbout= filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File")
self.SetMenuBar(menuBar)
# Events.
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.SetAutoLayout(1)
self.Show()
def OnExit(self,e):
self.Close(True) # Close the frame.
def updateList(self):
if self.radioT87.GetValue() == True:
choices = T87
self.listbox.Set(choices)
else:
choices = T89
self.listbox.Set(choices)
app = wx.App(False)
frame = MainWindow(None, "Supervisory Testing")
app.MainLoop()
When you create each radiobutton you can create a bind event. What this does (as you have implemented later on in your code) is execute a command function when the bind event occurs. In your case it would look like this:
self.Bind(wx.EVT_RADIOBUTTON,self.RadioButton,self.DoSomething)
Explanation:
wx.EVT_RADIOBUTTON
This is the event that is triggered when the user changes the Radiobutton's status. It may or may not have attributes.
self.RadioButton
This is the radiobutton which you would like to bind. In your case "self.radioAtoZ" or similar.
self.DoSomething
THis is the callback function. You can make it whatever you want such as:
def DoSomething(self):
if self.radioAtoZ.getStatus():
rearrangeNumbersFromAtoZ
print 'Re-arranged numbers from A to Z'
else:
etc.
EDIT:
self.RadioButton.Bind(EVT_RADIOBUTTON, self.DoSomething)
Your structure for self.DoSomething should be like this:
Class MainWindow:
def __init_(self, parent):
def DoSomething(self):
#dostuff
Also in response to your other comment:
when a function is called within a Bind event, it passes the event to the function by default. In addition, all functions have the "self" arg, thus 2 given args. You need to change the following:
def DoSomething(self, event):
#dostuff
I decided to rewrite the OP's code to demonstrate how to bind 2 RadioButton's to 2 different event handlers and update the ListBox:
import wx
########################################################################
class MyFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="Radios!")
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
self.radioAtoZ = wx.RadioButton(panel, label='Sort Name A-Z',
style = wx.RB_GROUP)
self.radioAtoZ.Bind(wx.EVT_RADIOBUTTON, self.sortAZ)
sizer.Add(self.radioAtoZ, 0, wx.ALL|wx.EXPAND, 5)
self.radioZtoA = wx.RadioButton(panel, label='Sort Name Z-A')
self.radioZtoA.Bind(wx.EVT_RADIOBUTTON, self.sortZA)
sizer.Add(self.radioZtoA, 0, wx.ALL|wx.EXPAND, 5)
choices = ["aardvark", "zebra", "bat", "giraffe"]
self.listbox = wx.ListBox(panel, choices=choices)
sizer.Add(self.listbox, 0, wx.ALL, 5)
panel.SetSizer(sizer)
self.Show()
#----------------------------------------------------------------------
def sortAZ(self, event):
""""""
choices = self.listbox.GetStrings()
choices.sort()
self.listbox.SetItems(choices)
#----------------------------------------------------------------------
def sortZA(self, event):
""""""
choices = self.listbox.GetStrings()
choices.sort()
choices.reverse()
self.listbox.SetItems(choices)
if __name__ == "__main__":
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
You will want to take a look at the following wiki article on the differences of binding it this way versus the other:
http://wiki.wxpython.org/self.Bind%20vs.%20self.button.Bind
Most of the time when you create a group of widgets that do different things, you bind them to different event handlers. If you want to bind all the RadioButtons to the same handler, then you'll probably need to name each widget with a unique name so that when they come to the handler, you can tell which button was pressed. Then you can use a series of if statements to decide what to do to the list box. Here's a tutorial that talks about that sort of thing:
http://www.blog.pythonlibrary.org/2011/09/20/wxpython-binding-multiple-widgets-to-the-same-handler/

Categories