Hello,
I’m new to both Python and wxPython so I’m still struggling with some of the basic concepts. What I am trying to do is create an application where I have a check box and a text box. If the check box is checked, then the text box should be white and editable, while if the check box is unchecked, the text box should be grey and uneditable (this behavior in quite common in various programs).
I managed to create a program which has this functionality and I’m pasting the code below. However, due to my lack of experience I’m not sure whether I’ve written my code in the best possible way. In particular I have a few questions:
-
In the functions makeselection, I have explicit reference to check_box_1 and text_box_1, which means that if I have 10 such check box / text box pairs in my final application, I need 10 makeselection functions, which seems quite inefficient. I’m guessing that there is a way to make just one function definition and then call it with various variables, however I couldn’t figure out how to do it. Or am I wrong?
-
In the function definition makeselection(self,event), what does ‘event’ stand for, since it is not explicitly given in the self.makeselection call? Is ‘event’ = wx.EVT_CHECKBOX? However if I call self.makeselection(wx.EVT_CHECKBOX), then the program doesn’t work as desired any more. Alternatively if I call self.makeselection(), then I get an error.
-
What is the difference between self. and ? I’m guessing works just withing the method definition, but if this variable needs to be used in a different method in the same class it needs to be called self..
-
The last one is purely a cosmetic one. If you notice the label and text box are not aligned properly, although the have the same y position coordinate. Is there a function to align them automatically, or should I just fiddle with the y positions?
Thanks a lot in advance to whoever might have some time to help me out!
Jopeto
Here’s the code:
#!/usr/bin/env python
import wx
class exampleclass(wx.Frame):
def init(self,parent,id):
wx.Frame.init(self,parent,id,title=‘Main window’, pos=(200,100), size=(500,500))
mainpanel=wx.Panel(self)
self.check_box_1 = wx.CheckBox(parent=mainpanel, id=-1, label='Enable box', pos=(100,100), size=wx.DefaultSize)
self.check_box_1.SetValue(True)
self.static_label_1 = wx.StaticText(parent=mainpanel, id=-1, label='Label', pos=(100,150), size=wx.DefaultSize, style=wx.ALIGN_LEFT)
self.text_box_1 = wx.TextCtrl(parent=mainpanel, id=-1, value='example text', pos=(200,150), size=(100,-1))
self.Bind(wx.EVT_CHECKBOX, self.makeselection, self.check_box_1)
def makeselection(self,event):
if self.check_box_1.IsChecked()==False:
self.text_box_1.SetEditable(False)
self.text_box_1.SetBackgroundColour(‘grey’)
else:
self.text_box_1.SetEditable(True)
self.text_box_1.SetBackgroundColour(‘white’)
if name==‘main’:
app=wx.PySimpleApp()
mainframe=exampleclass(parent=None,id=-1)
mainframe.Show()
app.MainLoop()