wxPython - A Simple Application

A thread at Codenone has been discussing about how to programming with Button in wxPython. In conclusion, there were 2 questions.

  1. How to fire an event to a specific button whenever Return or Enter key is pressed?
  2. How to specify TAB order to TextCtrl?

In fact, I have never developed GUI program for so long. I guessed as follows.

  1. Set the button as default.
  2. Specify tab index.

Above answers are just partially correct.

Actually, there is no tab index. You may specify tab index through id. Otherwise, you may assign -1 for automatic increasing id and then create controls in correct order.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import wx
 
class MainWindow(wx.Frame):
    def __init__(self,parent,id,title,*args,**kw):
        wx.Frame.__init__(self,parent,id,title,*args,**kw)
        self.init_ctrls()
        self.text1.SetFocus()
        self.Show(True)
 
    def init_ctrls(self):
        panel = wx.Panel(self,-1)
        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
 
        label1 = wx.StaticText(panel,-1,'เบอร์')
        label2 = wx.StaticText(panel,-1,'แทง')
        label3 = wx.StaticText(panel,-1,'บาท')
 
        text1 = wx.TextCtrl(panel,-1)
        text2 = wx.TextCtrl(panel,-1)
 
        self.btn = wx.Button(panel,wx.ID_OK)
        self.Bind(wx.EVT_BUTTON,self.OnOk,self.btn)
        self.btn.SetDefault()
 
        hbox.Add(label1,1)
        hbox.Add(text1,1,wx.ALIGN_LEFT)
        hbox.Add(label2,1)
        hbox.Add(text2,1,wx.ALIGN_LEFT)
        hbox.Add(label3,1)
        vbox.Add(hbox,0,wx.ALIGN_CENTRE)
        vbox.Add(self.btn,0,wx.ALIGN_RIGHT)
 
        panel.SetSizer(vbox)
 
        self.text1,self.text2 = text1,text2
 
    def OnOk(self,event):
        number = self.text1.GetValue()
        amount = self.text2.GetValue()
        msg = '%s: %s' % (number,amount)
        dlg = wx.MessageDialog(None,msg)
        dlg.ShowModal()
 
def App():
    app = wx.App()
    frame = MainWindow(None,wx.ID_ANY,"wx App")
    return app
 
if __name__ == '__main__':
    app = App()
    app.MainLoop()

So the first answer is self.btn.SetDefault().

Tags: ,

Post new comment