I've been working on an application for blind people, so I decided to python and wxPython for the GUI. The problem is that I cannot navigate the wx.toolbar using tabs. This is my actual code.
menuToolBar = self.CreateToolBar(style=wx.TB_FLAT)
menuToolBar.AddSeparator()
menuToolBar.AddTool(ID_NUEVO, "Nuevo Archivo", wx.Bitmap(
os.path.join(self.__rutaPrincipal, "img/nueva pagina.png")), "Nuevo Archivo")
menuToolBar.AddSeparator()
menuToolBar.AddTool(ID_GUARDAR_ARCHIVO, "Guardar Archivo", wx.Bitmap(
os.path.join(self.__rutaPrincipal, "img/guardar pagina.png")), "Guardar Archivo")
menuToolBar.AddTool(ID_ABRIR_ARCHIVO, "Abrir Página", wx.Bitmap(
os.path.join(self.__rutaPrincipal, "img/abrir pagina.png")), "Abrir Página")
menuToolBar.AddSeparator()
menuToolBar.AddTool(ID_FOCUS_PANEL_ESCRITURA, "Foco Escritura", wx.Bitmap(
os.path.join(self.__rutaPrincipal, "img/panel escritura.png")), "Foco Escritura")
menuToolBar.AddTool(ID_FOCUS_PANEL_RESULTADO, "Foco Resultado", wx.Bitmap(
os.path.join(self.__rutaPrincipal, "img/panel resultado.png")), "Foco Resultado")
menuToolBar.AddSeparator()
menuToolBar.AddTool(ID_CERRAR_PAGINA, "Cerrar Página", wx.Bitmap(
os.path.join(self.__rutaPrincipal, "img/cerrar pagina.png")), "Cerrar Página")
menuToolBar.AddSeparator()
menuToolBar.Realize()
is there any configuration to achieve it? or maybe is there another component that help me?.
P.D. I am new to python development and Stackoverflow
Rather than delete the existing anwser, which in fact answers a different question, I'm leaving it in place because I personally believe it's useful, in a related way.
Here is an example of what I was referring to in my comment, about making your own toolbar, which you can navigate using Tab, Left and Right Arrow keys.
It should be enough to get you started.
It uses a normal button and some Generic bitmap buttons, both will work, as we need to illustrate which button currently has focus, which is achieved by using at least 2 different bitmaps for each button. One Normal and one for Focus.
import wx
import wx.lib.buttons as buttons
Valid_keys = [wx.WXK_F1,wx.WXK_RETURN,wx.WXK_TAB,wx.WXK_LEFT,wx.WXK_RIGHT]
class MainFrame(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
self.funcs={"Button1":self.OnButton1,
"Button2":self.OnButton2,
"Button3":self.OnButton3,
"Button4":self.OnButton4}
wx.Frame.__init__(self, None, title="Self defined Toolbar", size=(400,400))
tool_panel = wx.Panel(self,-1,name="tool_panel")
tool_panel.SetBackgroundColour("lightgreen")
tool_panel.SetToolTip("Press F1 or Tab to Access Toolbar")
panel = wx.Panel(self,-1,size=(400,300), name="Main_panel")
panel.SetBackgroundColour("lightblue")
bmp = wx.Bitmap("Discord.png", wx.BITMAP_TYPE_ANY)
bmp1 = wx.Bitmap("Discord1.png", wx.BITMAP_TYPE_ANY)
bmp2 = wx.Bitmap("Discord2.png", wx.BITMAP_TYPE_ANY)
self.Button1 = buttons.GenBitmapButton(tool_panel,bitmap=bmp,size=(40,40),name="Button1")
self.Button2 = buttons.GenBitmapButton(tool_panel,bitmap=bmp,size=(40,40),name="Button2")
self.Button3 = buttons.GenBitmapButton(tool_panel,bitmap=bmp,size=(40,40),name="Button3")
self.Button4 = wx.Button(tool_panel,-1, label="",size=(40,40),name="Button4")
self.Button4.SetBitmap(wx.Bitmap('test.png'))
self.Button4.SetBitmapFocus(wx.Bitmap('testfocus.png'))
self.Text = wx.TextCtrl(panel, -1, size=(400,300), style=wx.TE_MULTILINE)
self.Button1.SetToolTip("Function1")
self.Button2.SetToolTip("Function2")
self.Button3.SetToolTip("Function3")
self.Button4.SetToolTip("Function4")
self.BitmapButtons = [self.Button1,self.Button2,self.Button3]
for i in range(0,len(self.BitmapButtons)):
self.BitmapButtons[i].SetBitmapLabel(bmp)
self.BitmapButtons[i].SetBitmapFocus(bmp2)
self.BitmapButtons[i].SetBitmapSelected(bmp1)
self.Bind(wx.EVT_BUTTON, self.OnButton)
self.Bind(wx.EVT_CHAR_HOOK, self.OnKey)
tool_sizer=wx.BoxSizer(wx.HORIZONTAL)
main_sizer=wx.BoxSizer(wx.VERTICAL)
tool_sizer.Add(self.Button1)
tool_sizer.Add(self.Button2)
tool_sizer.Add(self.Button3)
tool_sizer.Add(self.Button4)
tool_panel.SetSizer(tool_sizer)
main_sizer.Add(tool_panel,0,wx.EXPAND)
main_sizer.Add(panel,0,wx.EXPAND,0)
self.SetSizer(main_sizer)
self.Text.SetFocus()
self.Show()
def OnButton(self, event):
Id = event.GetId()
btn = event.GetEventObject()
x = self.funcs[btn.GetName()]
x()
self.Text.SetFocus()
def OnButton1(self):
print("Button 1")
def OnButton2(self):
print("Button 2")
def OnButton3(self):
print("Button 3")
def OnButton4(self):
print("Button 4")
def OnKey(self, event):
key = event.GetKeyCode()
if key not in Valid_keys: #Ignore all keys except F1, Enter and Navigation keys
event.Skip()
return
if key not in [wx.WXK_F1,wx.WXK_RETURN]:
event.Skip()
return
if key == wx.WXK_F1: #F1 focuses on the First Toolbar button
self.Button1.SetFocus()
return
i = self.get_focus()
if i == 1:
id="Button1"
elif i == 2:
id="Button2"
elif i == 3:
id="Button3"
elif i == 4:
id="Button4"
if i > 0: #Focus was a toolbar button, execute button function
x = self.funcs[id]
x()
self.Text.SetFocus()
event.Skip()
def get_focus(self):
focused = wx.Window.FindFocus()
if focused == self.Button1:
return 1
elif focused == self.Button2:
return 2
elif focused == self.Button3:
return 3
elif focused == self.Button4:
return 4
else:#Something other than the toolbar buttons has focus return Fail
return -1
#----------------------------------------------------------------------
if __name__ == "__main__":
app = wx.App()
frame = MainFrame()
app.MainLoop()
You need to implement Accelerators in your MenuBar and possibly your MenuItem's.
An accelerator table allows the application to specify a table of keyboard shortcuts for menu or button commands.
Often, these are set up using the text in the menu item, by-passing the wx.AcceleratorTable.
p1 = wx.MenuItem(playm, wx.NewIdRef(), '&Play\tCtrl+P')
Here the &Play sets P to be the Menu accelerator, and Ctrl+P to be the hotkey for the function represented by the menu item.
Put another way, when navigating the menus, pressing P will select the Play menu item. When not navigating the menus, just pressing Ctrl+P will run that function.
N.B.
You do not have to setup both.
Do not place the & ampersand character before the same letter more than once in a single menu or the menubar, as only the first one will function.
e.g. "&Save" and "Sa&ve as" would work, using S for "Save" and V for "Save as"
To access the Menu shortcuts Press the Alt button and then any of the underlined letters.
Some minimal code with Menu accelerators but no assigned hotkeys:
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200, 100))
self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
# A Statusbar in the bottom of the window
self.CreateStatusBar()
# Setting up the menus
'''Define main items'''
filemenu = wx.Menu()
editmenu = wx.Menu()
infomenu = wx.Menu()
'''Items'''
# file menu
menu_open = filemenu.Append(wx.ID_OPEN, "Open")
filemenu.Append(wx.ID_NEW, "New")
filemenu.Append(wx.ID_SAVE, "Save")
filemenu.Append(wx.ID_SAVEAS, "Save as")
filemenu.Append(wx.ID_EXIT, '&Quit', 'Quit application')
filemenu.AppendSeparator()
filemenu.Append(wx.ID_PRINT, "&Print")
filemenu.Append(wx.ID_PRINT_SETUP, "Print setup")
filemenu.Append(wx.ID_PREVIEW, "Preview")
# edit menu
editmenu.Append(wx.ID_COPY, "Copy")
editmenu.Append(wx.ID_CUT, "Cut")
editmenu.Append(wx.ID_PASTE, "Paste")
editmenu.AppendSeparator()
editmenu.Append(wx.ID_UNDO, "Undo")
editmenu.Append(wx.ID_REDO, "Re-do it")
# info menu
infomenu.Append(wx.ID_ABOUT, "About")
'''Bind items for activation'''
# bind file menu
self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
self.Bind(wx.EVT_MENU, self.OnOpen)
# Creating the menubar.
menuBar = wx.MenuBar()
# Add menus
menuBar.Append(filemenu, "&File")
menuBar.Append(editmenu, "&Edit")
menuBar.Append(infomenu, "&Help")
# Adding the MenuBar to the Frame content.
self.SetMenuBar(menuBar)
self.Show(True)
def OnOpen(self, event):
print ("Menu item selected")
# event skip as we want to continue checking events in case Quit was chosen
event.Skip()
def OnExit(self, event):
self.Destroy()
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
Run this code and Press the Alt key, press one of the undelined letters F, E or H and navigate the menus using the arrow keys or any underlined letters.
N.B. Certain functions are automatically assigned Hotkeys e.g. Ctrl+Q is Quit.
I am trying to get a better understanding of how wxPython 'scans'.
Please see my code below:
import os
import wx
from time import sleep
NoFilesToCombine = 0
class PDFFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, size=(400,400))
panel = wx.Panel(self)
self.Show()
try: #Set values of PDFNoConfirmed to zero on 1st initialisation
if PDFNoConfimed != 0:
None
except UnboundLocalError:
PDFNoConfimed = 0
try: #Set values of PDFNoConfirmed to zero on 1st initialisation
if PDFNoConfirmedInitially != 0:
None
except UnboundLocalError:
PDFNoConfirmedInitially = 0
while ((PDFNoConfimed == 0) and (PDFNoConfirmedInitially == 0)):
while PDFNoConfirmedInitially == 0:
BoxInputNo = wx.NumberEntryDialog(panel, "So You Want To Combine PDF Files?", "How Many?", "Please Enter", 0, 2, 20)
if BoxInputNo.ShowModal() == wx.ID_OK: #NumberEntryDialog Pressed OK
NoFilesToCombine = BoxInputNo.GetValue()
PDFNoConfirmedInitially = 1
elif BoxInputNo.ShowModal() == wx.ID_CANCEL:
exit()
print(NoFilesToCombine)
ConfirmationLabel = wx.StaticText(panel, -1, label="You Have Selected " + str(NoFilesToCombine) + " Files To Combine, Is This Right?", pos=(20, 100))
ConfirmationBoxConfirm = wx.ToggleButton(panel, label="Confirm", pos=(20, 200))
ConfirmationBoxCancel = wx.ToggleButton(panel, label="Cancel", pos=(180, 200))
#if ConfirmationBoxConfirm.GetValue() == 1:
# exit()
if ConfirmationBoxCancel.GetValue() == 1:
PDFNoConfirmedInitially = 0
app = wx.App()
frame = PDFFrame(None, title="Robs PDF Combiner Application")
app.MainLoop()
Now this is a work in progress so it obviously isn't complete. However what I'm trying to accomplish with the above is:
Display a number entry popup. If user presses 'cancel' exit the application (this works but needs 2 presses for some reason?). If press OK, then:
Display the number entered in step 1, with 2 additional buttons. The 'confirm' doesn't do anything as yet, but the 'cancel' should take you back to step 1. (by resetting the PDFNoConfirmedInitially flag).
Now step 2 doesn't work. When I debug it almost appears as though the PDFFrameonly gets scanned once. My presumably false assumption being that this would be continually scanned due to app.MainLoop() continually scanning wx.App() which in turn would call the child frame?
Help/ pointers/ deeper understanding always appreciated,
Thanks
Rob
1) ShowModal() shows dialog window and you use it two times
if BoxInputNo.ShowModal() == wx.ID_OK:
and
elif BoxInputNo.ShowModal() == wx.ID_CANCEL:
so it shows your window two times.
And only at second time you check wx.ID_CANCEL.
You should run it only once and check its result
result = BoxInputNo.ShowModal()
if result == wx.ID_OK:
pass
elif result == wx.ID_CANCEL:
self.Close()
return
2) You have to assign function to button and this function should reset variable and show dialog window again. But I think wx.Button could be better then wx.ToggleButton
ConfirmationBoxCancel = wx.Button(panel, label="Cancel", pos=(180, 200))
ConfirmationBoxCancel.Bind(wx.EVT_BUTTON, self.on_button_cancel)
def on_button_cancel(self, event):
#print('event:', event)
pass
# reset variable and show dialog window
Frankly I don't understand some of your variables. Maybe if you use True/False instead of 0/1 then they will be more readable. But main problem for me are while loops. GUI frameworks (wxPython, tkinter, PyQt, etc) should run only one loop - Mainloop(). Any other loop may block Mainloop() and GUI will freeze.
I created own version without any while loop but I don't know if it resolve all problems
import wx
class PDFFrame(wx.Frame):
def __init__(self, parent, title):
super().__init__(parent, -1, title, size=(400,400))
self.panel = wx.Panel(self)
self.Show()
# show dialog at start
if self.show_dialog(self.panel):
# create StaticLabel and buttons
self.show_confirmation(self.panel)
else:
# close main window and program
self.Close()
def show_dialog(self, panel):
"""show dialog window"""
global no_files_to_combine
box_input_no = wx.NumberEntryDialog(panel, "So You Want To Combine PDF Files?", "How Many?", "Please Enter", 0, 2, 20)
result = box_input_no.ShowModal()
if result == wx.ID_OK: #NumberEntryDialog Pressed OK
no_files_to_combine = box_input_no.GetValue()
return True
elif result == wx.ID_CANCEL:
print('exit')
return False
def show_confirmation(self, panel):
"""create StaticLabel and buttons"""
self.confirmation_label = wx.StaticText(self.panel, -1, label="You Have Selected {} Files To Combine, Is This Right?".format(no_files_to_combine), pos=(20, 100))
self.confirmation_box_confirm = wx.Button(self.panel, label="Confirm", pos=(20, 200))
self.confirmation_box_cancel = wx.Button(self.panel, label="Cancel", pos=(180, 200))
# assign function
self.confirmation_box_confirm.Bind(wx.EVT_BUTTON, self.on_button_confirm)
self.confirmation_box_cancel.Bind(wx.EVT_BUTTON, self.on_button_cancel)
def update_confirmation(self):
"""update existing StaticLabel"""
self.confirmation_label.SetLabel("You Have Selected {} Files To Combine, Is This Right?".format(no_files_to_combine))
def on_button_cancel(self, event):
"""run when pressed `Cancel` button"""
#print('event:', event)
# without `GetValue()`
if self.show_dialog(self.panel):
# update existing StaticLabel
self.update_confirmation()
else:
# close main window and program
self.Close()
def on_button_confirm(self, event):
"""run when pressed `Confirn` button"""
#print('event:', event)
# close main window and program
self.Close()
# --- main ---
no_files_to_combine = 0
app = wx.App()
frame = PDFFrame(None, title="Robs PDF Combiner Application")
app.MainLoop()
Please see this code example:
import gtk
class MenuBox(gtk.EventBox):
def __init__(self):
super(MenuBox, self).__init__()
self.set_visible_window(False)
self.connect('enter-notify-event', self._on_mouse_enter)
self.connect('leave-notify-event', self._on_mouse_leave)
btn = gtk.Button('x')
btn.set_border_width(12)
self.add(btn)
def _on_mouse_enter(self, wid, event):
print '_on_mouse_enter'
def _on_mouse_leave(self, *args):
print '_on_mouse_leave'
def main():
win = gtk.Window()
win.connect('destroy', gtk.main_quit)
win.add(MenuBox())
win.show_all()
gtk.main()
if __name__ == '__main__':
main()
I want that the enter and leave events are not triggered if I am going from parent to child and back. I know that in this particular case I can filter these events with event.detail. But this does not work if there is no border. If I remove the border the events aren't triggered at all.
In my real code I have a more complex widget (based on gtk.Fixed) which has border at the beginning but not at the end. So just moving the event to the child wouldn't do the trick either.
# self.set_visible_window(False)
self.connect('enter-notify-event', self._on_mouse_enter)
self.connect('leave-notify-event', self._on_mouse_leave)
btn = gtk.Button('x')
# btn.set_border_width(12)
Is that what you need?
How could I have a scrollbar inside a gtk.Layout.
For example, in my code I have:
import pygtk
pygtk.require('2.0')
import gtk
class ScrolledWindowExample:
def __init__(self):
self.window = gtk.Dialog()
self.window.connect("destroy", self.destroy)
self.window.set_size_request(300, 300)
self.scrolled_window = gtk.ScrolledWindow()
self.scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.window.vbox.pack_start(self.scrolled_window, True, True, 0)
self.layout = gtk.Layout()
self.scrolled_window.add(self.layout)
self.current_pos = 0
self.add_buttom()
self.window.show_all()
def add_buttom(self, widget = None):
title = str(self.current_pos)
button = gtk.ToggleButton(title)
button.connect_object("clicked", self.add_buttom, None)
self.layout.put(button, self.current_pos, self.current_pos)
button.show()
self.current_pos += 20
def destroy(self, widget):
gtk.main_quit()
if __name__ == "__main__":
ScrolledWindowExample()
gtk.main()
What I really want is to find some way to make the scroll dynamic. See the example that I put above, when you click any button, another button will be added. But the scrollbar doesn't work.
What can I do to get the scroll bars working?
Does it works if you either use gtk.Window() instead of gtk.Dialog(); or execute self.window.run() after self.window.show_all()?
The difference between Dialog and common Window is that Dialog has its own loop which processes events. As you do not run its run() command, this loop never gets the chance to catch the events, so ScrolledWindow does not receives them, and does not change its size.
I have the following code:
self.sliderR.Bind(wx.EVT_SCROLL,self.OnSlide)
In the function OnSlide I have the inserted the code pdb.set_trace() to help me debug.
In the pdb prompt if I type event.GetEventType() it returns a number (10136) but I have no idea which event that corresponds to.
Does the 10136 refer to the wx.EVT_SCROLL or another event that also triggers the wx.EVT_SCROLL event? If the latter is true, how do I find the specific event?
Thanks.
There isn't a built-in way. You will need to build an event dictionary. Robin Dunn has some code here that will help: http://osdir.com/ml/wxpython-users/2009-11/msg00138.html
Or you can check out my simple example:
import wx
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Tutorial")
self.eventDict = {}
for name in dir(wx):
if name.startswith('EVT_'):
evt = getattr(wx, name)
if isinstance(evt, wx.PyEventBinder):
self.eventDict[evt.typeId] = name
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
btn = wx.Button(panel, wx.ID_ANY, "Get POS")
btn.Bind(wx.EVT_BUTTON, self.onEvent)
panel.Bind(wx.EVT_LEFT_DCLICK, self.onEvent)
panel.Bind(wx.EVT_RIGHT_DOWN, self.onEvent)
def onEvent(self, event):
"""
Print out what event was fired
"""
evt_id = event.GetEventType()
print self.eventDict[evt_id]
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()