python just restarts and does not run the program at all - python

can anyone help me with this? i created a gui using wxformbuilder which generated python code for. then i created a separate code on how it should be working.
this first code is for the gui only.
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Jun 17 2015)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
###########################################################################
## Class frmQuestions
###########################################################################
class frmQuestions ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 1055,562 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_HIGHLIGHT ) )
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.lblQbox = wx.StaticText( self, wx.ID_ANY, u"Question:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.lblQbox.Wrap( -1 )
self.lblQbox.SetFont( wx.Font( 18, 73, 93, 90, False, "Brush Script MT" ) )
bSizer1.Add( self.lblQbox, 0, wx.ALL|wx.EXPAND, 5 )
self.txtQ = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer1.Add( self.txtQ, 1, wx.ALL|wx.EXPAND, 5 )
self.btnNext = wx.Button( self, wx.ID_ANY, u"Next", wx.DefaultPosition, wx.DefaultSize, 0 )
self.btnNext.SetFont( wx.Font( 12, 72, 90, 90, False, "Cooper Black" ) )
bSizer1.Add( self.btnNext, 0, wx.ALL|wx.EXPAND, 5 )
self.btnShowResults = wx.Button( self, wx.ID_ANY, u"Show Results", wx.DefaultPosition, wx.DefaultSize, 0 )
self.btnShowResults.SetFont( wx.Font( 12, 72, 90, 90, False, "Cooper Black" ) )
bSizer1.Add( self.btnShowResults, 0, wx.ALL|wx.EXPAND, 5 )
self.btnExit = wx.Button( self, wx.ID_ANY, u"Exit", wx.DefaultPosition, wx.DefaultSize, 0 )
self.btnExit.SetFont( wx.Font( 12, 72, 90, 90, False, "Cooper Black" ) )
bSizer1.Add( self.btnExit, 0, wx.ALL|wx.EXPAND, 5 )
self.SetSizer( bSizer1 )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.btnNext.Bind( wx.EVT_BUTTON, self.OnNext )
self.btnShowResults.Bind( wx.EVT_BUTTON, self.OnShowResults )
self.btnExit.Bind( wx.EVT_BUTTON, self.OnExit )
def __del__( self ):
pass
# Virtual event handlers, overide them in your derived class
def OnNext( self, event ):
event.Skip()
def OnShowResults( self, event ):
event.Skip()
def OnExit( self, event ):
event.Skip()
###########################################################################
## Class frmResults
###########################################################################
class frmResults ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
self.SetForegroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_ACTIVECAPTION ) )
self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_HIGHLIGHT ) )
bSizer2 = wx.BoxSizer( wx.VERTICAL )
self.txtResults = wx.StaticText( self, wx.ID_ANY, u"Results", wx.DefaultPosition, wx.DefaultSize, 0 )
self.txtResults.Wrap( -1 )
self.txtResults.SetFont( wx.Font( 12, 72, 90, 90, False, "Cooper Black" ) )
bSizer2.Add( self.txtResults, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 )
self.txtA = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer2.Add( self.txtA, 1, wx.ALL|wx.EXPAND, 5 )
self.txtB = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer2.Add( self.txtB, 1, wx.ALL|wx.EXPAND, 5 )
self.txtC = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer2.Add( self.txtC, 1, wx.ALL|wx.EXPAND, 5 )
self.txtD = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer2.Add( self.txtD, 1, wx.ALL|wx.EXPAND, 5 )
self.btnGoBack = wx.Button( self, wx.ID_ANY, u"Go Back", wx.DefaultPosition, wx.DefaultSize, 0 )
self.btnGoBack.SetFont( wx.Font( 12, 72, 90, 90, False, "Cooper Black" ) )
bSizer2.Add( self.btnGoBack, 0, wx.ALL|wx.EXPAND, 5 )
self.SetSizer( bSizer2 )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.btnGoBack.Bind( wx.EVT_BUTTON, self.OnGoBack )
def __del__( self ):
pass
# Virtual event handlers, overide them in your derived class
def OnGoBack( self, event ):
event.Skip()
then here is the code to be run on rpi:
from noname import *
from wx import *
Q1 = 'Q1'
Q2 = 'Q2'
Q3 = 'Q3'
Q4 = 'Q4'
Q5 = 'Q5'
Q6 = 'Q6'
Q7 = 'Q7'
Q8 = 'Q8'
Q9 = 'Q9'
Q10 = 'Q10'
Q11 = 'Q11'
Q12 = 'Q12'
Q13 = 'Q13'
Q14 = 'Q14'
Q15 = 'Q15'
Q16 = 'Q16'
Q17 = 'Q17'
Q18 = 'Q18'
Q19 = 'Q19'
Q20 = 'Q20'
class Questions(frmQuestions):
x = 0
def __init__(self, parent):
frmQuestions.__init__(self,parent)
self.txtQ.SetLabel('')
def OnNext(self, event):
self.x = self.x + 1
if (self.x==1):
self.txtQ.SetLabel(Q1)
elif (self.x==2):
self.txtQ.SetLabel(Q2)
elif (self.x==3):
self.txtQ.SetLabel(Q3)
elif (self.x==4):
self.txtQ.SetLabel(Q4)
elif (self.x==5):
self.txtQ.SetLabel(Q5)
elif (self.x==6):
self.txtQ.SetLabel(Q6)
elif (self.x==7):
self.txtQ.SetLabel(Q7)
elif (self.x==8):
self.txtQ.SetLabel(Q8)
elif (self.x==9):
self.txtQ.SetLabel(Q9)
elif (self.x==10):
self.txtQ.SetLabel(Q10)
elif (self.x==11):
self.txtQ.SetLabel(Q11)
elif (self.x==12):
self.txtQ.SetLabel(Q12)
elif (self.x==13):
self.txtQ.SetLabel(Q13)
elif (self.x==14):
self.txtQ.SetLabel(Q14)
elif (self.x==15):
self.txtQ.SetLabel(Q15)
elif (self.x==16):
self.txtQ.SetLabel(Q16)
elif (self.x==17):
self.txtQ.SetLabel(Q17)
elif (self.x==18):
self.txtQ.SetLabel(Q18)
elif (self.x==19):
self.txtQ.SetLabel(Q19)
elif (self.x==20):
self.txtQ.SetLabel(Q20)
else:
pass
print self.x
def OnShowResults(self, event):
results.Show()
def OnExit(self, event):
self.Destroy()
class Results(frmResults):
def __init__(self, parent):
frmResults.__init__(self,parent)
def OnGoBack(self, event):
self.txtA.SetLabel('')
self.txtB.SetLabel('')
self.txtC.SetLabel('')
self.txtD.SetLabel('')
self.Hide()
app = wx.App(False)
results = Results(None)
questions = Questions(None)
questions.Show()
app.MainLoop()
everytime i run it on rpi. python shell just always display -------------------------------restart------------------------- and the gui doesnt appear at all. i just wanna know what is the problem with the code.
and also i created the code on windows and i copied both python files on rpi. on windows it works properly. i sincerely thank you for your hep im just a student and a newbie so i can't really point out what is wrong with my code. thanks :)))

Are you running this via ./myscript.py? If so, you need to add the interpreter to the top. The first line should be:
#!/usr/bin/env python
or something similar so that it knows which interpreter to use.
I know this is not the question, but I'm more concerned about your actual program, to be honest. For example, instead of writing multiple consecutive QN = "QN", you can create them all as a dict and update the global variables. For example:
tmp = ["Q{}".format(i+1) for i in range(20)]
globals().update(dict(zip(tmp, tmp)))
That's significantly easier. Or, better yet, you can map numbers to your desired strings in the form of a dict so the entire thing can be rewritten as:
#!/usr/bin/env python
from noname import *
from wx import *
tmp = ["Q{}".format(i+1) for i in range(20)] # Create a list of "Q1"..."Q20"
vars = dict(enumerate(tmp, 1)) # { 1 : "Q1", 2 : "Q2", ... 20 : "Q20" }
class Questions(frmQuestions):
def __init__(self, parent):
self.x = 0 # Made this an instance variable
frmQuestions.__init__(self,parent)
self.txtQ.SetLabel('')
def OnNext(self, event):
self.x = self.x + 1
if self.x in vars:
self.txtQ.SetLabel(vars[self.x]) # significantly simplified
print(self.x)
def OnShowResults(self, event):
results.show()
def OnExit(self, event):
self.Destroy()
class Results(frmResults):
def __init__(self, parent):
frmResults.__init__(self,parent)
def OnGoBack(self, event):
for _ in [self.txtA, self.txtB, self.txtC, self.txtD]:
_.SetLabel('')
self.Hide()
app = wx.App(False)
results = Results(None)
questions = Questions(None)
questions.Show()
app.MainLoop()

Related

Start / Stop buttons for reading from serial with wxpython

I created a simple GUI with wxpython to read data from a serial port. Based on several posts I was able to connect to the serial port when I press the Connect button and print the data when i press Start button but I press the Stop button I can´t stop printing data.
Here's is my code (inside are the links to the posts previously refered):
# -*- coding: utf-8 -*-
import wx
import wx.xrc
import serial
import time
import threading
class MyFrame ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
bSizer1 = wx.BoxSizer( wx.HORIZONTAL )
bSizer2 = wx.BoxSizer( wx.VERTICAL )
self.connectBtn = wx.Button( self, wx.ID_ANY, u"Connect", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer2.Add( self.connectBtn, 0, wx.ALL, 5 )
self.startBtn = wx.Button( self, wx.ID_ANY, u"Start", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer2.Add( self.startBtn, 0, wx.ALL, 5 )
self.stopBtn = wx.Button( self, wx.ID_ANY, u"Stop", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer2.Add( self.stopBtn, 0, wx.ALL, 5 )
bSizer1.Add( bSizer2, 0, wx.EXPAND, 5 )
bSizer3 = wx.BoxSizer( wx.VERTICAL )
self.m_textCtrl1 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer3.Add( self.m_textCtrl1, 1, wx.ALL|wx.EXPAND, 5 )
self.ser = None
self.settings = {'PORT':'COM3' , 'BAUDRATE':9600}
self.connected = False
bSizer1.Add( bSizer3, 1, wx.EXPAND, 5 )
self.SetSizer( bSizer1 )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.connectBtn.Bind( wx.EVT_BUTTON, self.connectBtnOnButtonClick )
self.startBtn.Bind( wx.EVT_BUTTON, self.startBtnOnButtonClick )
self.stopBtn.Bind( wx.EVT_BUTTON, self.stopBtnOnButtonClick )
def __del__( self ):
pass
# Virtual event handlers, overide them in your derived class
def connectBtnOnButtonClick( self, event ):
# http://stackoverflow.com/questions/11092417/reconnecting-to-device-with-pyserial
try:
if self.ser == None:
self.ser = serial.Serial(self.settings['PORT'],
self.settings['BAUDRATE'],timeout=10)
# print "Successfully connected to port %r." % self.ser.port
self.connectBtn.SetLabel('Disconnect')
self.connected = True
return True
else:
if self.ser.isOpen():
self.ser.close()
self.connected = False
self.connectBtn.SetLabel('Connect')
# print "Disconnected."
return False
else:
self.ser.open()
self.connected = True
self.connectBtn.SetLabel('Disconnect')
# print "Connected."
return True
except serial.SerialException, e:
return False
def startBtnOnButtonClick( self, event ):
while self.connected:
self.connected = True
while True:
if (self.ser.inWaiting() > 0):
data_str = self.ser.read(self.ser.inWaiting())
print(data_str.strip())
time.sleep(0.1)
def stopBtnOnButtonClick( self, event ):
self.connected = False
# self.connected = False
# http://stackoverflow.com/questions/17553543/pyserial-non-blocking-read-loop
if __name__ == "__main__":
app = wx.App(redirect=False)
frame = MyFrame(None)
#app.SetTopWindow(frame)
frame.Show(True)
app.MainLoop()
Thank you.
Ivo
Essentially, I think that your startBtnOnButtonClick is a "long running process" and you will need to call wx.Yield() before or after your sleep.
This will allow your program is check back with the main loop to see if anything else has occurred i.e. you pressed the stop button.
See: https://wiki.wxpython.org/LongRunningTasks
Change startBtnOnButtonClick to remove the double while loop
def startBtnOnButtonClick( self, event ):
while self.connected:
if (self.ser.inWaiting() > 0):
data_str = self.ser.read(self.ser.inWaiting())
print(data_str.strip())
time.sleep(0.1)
wx.Yield()

wxPython frame don't show

I have the following Python code that would make a GUI for the command line process of turning a video into frames that is native to VLC Media Player.
# -*- coding: utf-8 -*-
from subprocess import call
import wx
import wx.xrc
vidpath = ''
framedir = ''
def VideoToFrame(videopath, targetdirpath):
"Converts a video into frames. Make sure you have VLC Media Player installed!"
call('vlc.exe "' + videopath + '" --video-filter=scene --vout=dummy --start-time=300 --stop-time=600 --scene-ratio=250 --scene-path=”' + targetdirpath + '” vlc://quit')
if __name__ == "__main__":
class MyFrame1 ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 436,159 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
gbSizer1 = wx.GridBagSizer( 0, 0 )
gbSizer1.SetFlexibleDirection( wx.BOTH )
gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
gbSizer2 = wx.GridBagSizer( 0, 0 )
gbSizer2.SetFlexibleDirection( wx.BOTH )
gbSizer2.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
self.VidLabel = wx.StaticText( self, wx.ID_ANY, u"Video path", wx.DefaultPosition, wx.DefaultSize, 0 )
self.VidLabel.Wrap( -1 )
gbSizer2.Add( self.VidLabel, wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 1 ), wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 )
self.m_filePicker1 = wx.FilePickerCtrl( self, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE )
gbSizer2.Add( self.m_filePicker1, wx.GBPosition( 1, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )
gbSizer1.Add( gbSizer2, wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 1 ), wx.EXPAND, 5 )
gbSizer3 = wx.GridBagSizer( 0, 0 )
gbSizer3.SetFlexibleDirection( wx.BOTH )
gbSizer3.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
self.FrameLabel = wx.StaticText( self, wx.ID_ANY, u"Frame extraction path", wx.DefaultPosition, wx.DefaultSize, 0 )
self.FrameLabel.Wrap( -1 )
gbSizer3.Add( self.FrameLabel, wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 1 ), wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 )
self.m_dirPicker1 = wx.DirPickerCtrl( self, wx.ID_ANY, wx.EmptyString, u"Select a folder", wx.DefaultPosition, wx.DefaultSize, wx.DIRP_DEFAULT_STYLE )
gbSizer3.Add( self.m_dirPicker1, wx.GBPosition( 1, 0 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )
gbSizer1.Add( gbSizer3, wx.GBPosition( 0, 1 ), wx.GBSpan( 1, 1 ), wx.EXPAND, 5 )
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.framebutton = wx.Button( self, wx.ID_ANY, u"Extract frames!", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer1.Add( self.framebutton, 0, wx.ALL, 5 )
gbSizer1.Add( bSizer1, wx.GBPosition( 2, 0 ), wx.GBSpan( 1, 1 ), wx.EXPAND, 5 )
self.SetSizer( gbSizer1 )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.m_filePicker1.Bind( wx.EVT_FILEPICKER_CHANGED, self.chvidpath )
self.m_dirPicker1.Bind( wx.EVT_DIRPICKER_CHANGED, self.chframedir )
self.framebutton.Bind( wx.EVT_BUTTON, self.extractframes )
def __del__( self ):
pass
# Virtual event handlers, overide them in your derived class
def chvidpath( self, event ):
vidpath = event.path
event.Skip()
def chframedir( self, event ):
framedir = event.path
event.Skip()
def extractframes( self, event ):
VideoToFrame(vidpath, framedir)
event.Skip()
Unfortunately I couldn't manage the frame to show when I ran the script.
The result was... nothing!
Please help! I have no idea of what I am doing, and no other idea of how to make a GUI of a command line process.
I am a good Python player though.
I don't see where you created an instance of your MyFrame1
add:
app = wx.App()
frame = MyFrame1(None)
frame.Show()
app.MainLoop()

Access a specific sizer from wxFormBuilder in Python

I have built a GUI using wxFormBuilder and want to dynamically add buttons to a sizer within the GUI. Here is the wxFormBuilder code.
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Jun 17 2015)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
###########################################################################
## Class HighVoltage
###########################################################################
class HighVoltage ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 1031,530 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_ACTIVECAPTION ) )
bSizer84 = wx.BoxSizer( wx.VERTICAL )
self.m_panel70 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer85 = wx.BoxSizer( wx.HORIZONTAL )
self.m_staticText79 = wx.StaticText( self.m_panel70, wx.ID_ANY, u"HV Documentation", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText79.Wrap( -1 )
self.m_staticText79.SetFont( wx.Font( 20, 70, 90, 92, False, "Century Gothic" ) )
bSizer85.Add( self.m_staticText79, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
bSizer85.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_bitmap24 = wx.StaticBitmap( self.m_panel70, wx.ID_ANY, wx.Bitmap( u"LOGOtransSmall.png", wx.BITMAP_TYPE_ANY ), wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer85.Add( self.m_bitmap24, 0, wx.ALL, 5 )
self.m_panel70.SetSizer( bSizer85 )
self.m_panel70.Layout()
bSizer85.Fit( self.m_panel70 )
bSizer84.Add( self.m_panel70, 0, wx.EXPAND |wx.ALL, 5 )
self.m_panel71 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer86 = wx.BoxSizer( wx.VERTICAL )
bSizer86.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_panel73 = wx.Panel( self.m_panel71, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer86.Add( self.m_panel73, 0, wx.EXPAND |wx.ALL, 5 )
self.m_panel71.SetSizer( bSizer86 )
self.m_panel71.Layout()
bSizer86.Fit( self.m_panel71 )
bSizer84.Add( self.m_panel71, 1, wx.EXPAND |wx.ALL, 5 )
self.m_panel72 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer87 = wx.BoxSizer( wx.HORIZONTAL )
bSizer87.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_button65 = wx.Button( self.m_panel72, wx.ID_ANY, u"Exit", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer87.Add( self.m_button65, 0, wx.ALL, 5 )
self.m_panel72.SetSizer( bSizer87 )
self.m_panel72.Layout()
bSizer87.Fit( self.m_panel72 )
bSizer84.Add( self.m_panel72, 0, wx.EXPAND |wx.ALL, 5 )
self.SetSizer( bSizer84 )
self.Layout()
self.Centre( wx.BOTH )
def __del__( self ):
pass
I want to add buttons to bSizer86 which is a child of m_panel71.
Here's what I've tried so far.
class HvDocs(HighVoltage):
def __init__(self, parent):
HighVoltage.__init__(self, parent)
con = sqlite3.connect('hsmanagement.sqlite')
cur = con.execute('SELECT employee FROM employees WHERE hv=1 ORDER BY employee')
result = cur.fetchall()
con.close()
print result
sizer = self.GetSizer()
print type(sizer)
for f in range(0, len(result) ):
sizer.Add(wx.Button(self, label=str(result[f][0]), id=int(f), size=(200, 40)), 2, wx.CENTER)
I have tried a few variations of sizer = self.GetSizer() such as sizer = self.m_panel71 and sizer = self.GetSizer(self.m_panel71) but all I can manage is to add the buttons to the top level sizer bSizer84. How do I gain access to bSizer86?
See the following minimal example how to find panels, buttons and sizers by name only. wxFormBuilder offers the possibility to set the wx.Window property window_name for GUI elements you want to keep track on. You should be able to find control you need to know having this name with parent.FindWindowByName(…) without relying on a class attribute.
import wx
TOK_PNL = 'window_name pnl'
TOK_BTN = 'window_name btn'
def on_btn(evt, parent):
btn = parent.FindWindowByName(TOK_BTN)
pnl = parent.FindWindowByName(TOK_PNL)
newbtn = wx.Button(pnl, -1, 'newbtn')
szsub = btn.GetContainingSizer()
szsub.Add(newbtn, 1, wx.EXPAND|wx.ALL, 4)
pnl.Layout()
class testfrm(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
pnl = wx.Panel(self, -1)
pnl.SetName(TOK_PNL)
btn = wx.Button(pnl, -1, 'Add Button')
btn.SetName(TOK_BTN)
szmain = wx.BoxSizer(wx.VERTICAL)
szsub = wx.BoxSizer(wx.HORIZONTAL)
szsub.Add(btn, 0, wx.EXPAND|wx.ALL, 4)
szmain.Add(szsub)
pnl.SetSizer(szmain)
the_parent = self
btn.Bind(wx.EVT_BUTTON, lambda evt: on_btn(evt, the_parent))
if __name__ == '__main__':
app = wx.App(redirect=False)
frm = testfrm(None, -1, 'testfrm')
frm.Show()
app.MainLoop()
After digging a bit further and playing around I finally solved my problem with the following code
sizer = self.m_button67.GetContainingSizer()
self.m_button67.Destroy()
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Ladder ID")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Engineer")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Description")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Last Check")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Next Check")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
for f in range(0, len(ladder_data)):
self.m_button = wx.Button( self.m_panel74, id=int(f), label=str(ladder_data[f][0]))
self.Bind(wx.EVT_BUTTON, self.detect_on_button)
sizer.Add( self.m_button, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][1]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][2]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][3]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][4]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_panel74.SetSizer( sizer )
self.m_panel74.Layout()
sizer.Fit( self.m_panel74 )
The key really was the discovery of GetContainingSizer().
Using this with a dummy button set up in wxFormBuilder (self.m_button67)
sizer = self.m_button67.GetContainingSizer()
gets you the sizer
remove the dummy button with
self.m_button67.Destroy()
add you widgets with
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][1]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
and the layout is completed with
self.m_panel74.SetSizer( sizer )
self.m_panel74.Layout()
sizer.Fit( self.m_panel74 )
Hope this help anyone with the same problem.
Maybe a little late,
I believe you are using GetSizer on Wrong element.
Try switching sizer = self.GetSizer() by sizer = self.m_panel71.GetSizer()

Python/wxPython: How to reset wx.Choice to a default value

Am working with multiple wx.Choice control in wxPython and I needed the make a reset button to restore the default option “-- Select --” when clicked.
Am unable to achieve that, the closest I came is to reset to empty options which is NOT what is want. I want the default option “-- Select --” to come up when reset button is pressed. See my code below.
data.py
import wx
class MyFrame1 ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 250,300 ), style = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.SYSTEM_MENU|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
DataBox = wx.BoxSizer( wx.HORIZONTAL )
gSizer2 = wx.GridSizer( 0, 2, 0, 0 )
self.Color_Label = wx.StaticText( self, wx.ID_ANY, u"Color:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.Color_Label.Wrap( -1 )
self.Color_Label.SetFont( wx.Font( 13, 70, 90, 90, False, wx.EmptyString ) )
gSizer2.Add( self.Color_Label, 0, wx.ALL, 5 )
Color_optionsChoices = [ u"-- Select --", u"Red", u"Green", u"Pink", u"Blue", u"Yellow", u"White", u"Brown" ]
self.Color_options = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, Color_optionsChoices, 0 )
self.Color_options.SetSelection( 0 )
gSizer2.Add( self.Color_options, 0, wx.ALL, 5 )
self.Age = wx.StaticText( self, wx.ID_ANY, u"Age:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.Age.Wrap( -1 )
self.Age.SetFont( wx.Font( 13, 70, 90, 90, False, wx.EmptyString ) )
gSizer2.Add( self.Age, 0, wx.ALL, 5 )
Age_optionsChoices = [ u"-- Select --", u"15", u"16", u"17", u"18", u"19", u"20", u"21", u"22", u"23", u"24", u"25", wx.EmptyString ]
self.Age_options = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, Age_optionsChoices, 0 )
self.Age_options.SetSelection( 0 )
gSizer2.Add( self.Age_options, 0, wx.ALL, 5 )
self.Country = wx.StaticText( self, wx.ID_ANY, u"Country:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.Country.Wrap( -1 )
self.Country.SetFont( wx.Font( 13, 70, 90, 90, False, wx.EmptyString ) )
gSizer2.Add( self.Country, 0, wx.ALL, 5 )
Country_optionsChoices = [ u"-- Select --", u"Mexico", u"Peru", u"India", u"USA", u"UK", u"Greece", u"Agentina", u"Greece", u"Brazil", u"Egypt" ]
self.Country_options = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, Country_optionsChoices, 0 )
self.Country_options.SetSelection( 0 )
gSizer2.Add( self.Country_options, 0, wx.ALL, 5 )
self.Reset_button = wx.Button( self, wx.ID_ANY, u"Reset", wx.DefaultPosition, wx.DefaultSize, 0 )
gSizer2.Add( self.Reset_button, 0, wx.ALL, 5 )
self.Exit_button = wx.Button( self, wx.ID_ANY, u"Exit", wx.DefaultPosition, wx.DefaultSize, 0 )
gSizer2.Add( self.Exit_button, 0, wx.ALL, 5 )
DataBox.Add( gSizer2, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 5 )
self.SetSizer( DataBox )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.Reset_button.Bind( wx.EVT_BUTTON, self.OnResetButton )
self.Exit_button.Bind( wx.EVT_BUTTON, self.OnExitButton )
def OnResetButton( self, event ):
# val = '-- Select --' # NOT WORKING
val = ' ' # THIS WORKS, BUT RESETS TO EMPTY CHOICE
self.Color_options.SetLabel(val)
self.Age_options.SetLabel(val)
self.Country_options.SetLabel(val)
def OnExitButton( self, event ):
self.Close()
app = wx.App(0)
MyFrame1(None).Show()
app.MainLoop()
Thanks for your time in advance.
Please reduce your source code to a minimal runnable example (explained below).
Answer: I am amazed that wx.Choice.SetLabel(' ') does something useful. What you want to do instead is:
self.Color_Options.SetStringSelection(val)
(see the wxWidgets documentation for wxChoice/wxItemContainer).
Remark: u'--Select--' is not '--Select--' in Python. As it happens, if the source encoding is set to UTF-8, wxPython will not complain and understand str encoden in UTF-8 as well as u''.
Minimal runnable example: As important as ever: Making your example as small as possible will teach you which parts are relevant for your question and which are not. In many cases, by writing the minimal example, I very often find the answer myself.
Minimising your example:
import wx
class MyFrame1(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
pnl = wx.Panel(self, wx.ID_ANY)
szmain = wx.BoxSizer(wx.VERTICAL)
color_choices = [u"-- Select --", u"Red", u"Green", u"Pink", u"Blue", u"Yellow", u"White", u"Brown"]
self.color_options = wx.Choice(pnl, wx.ID_ANY, choices=color_choices)
self.color_options.SetSelection(0)
self.reset_button = wx.Button(pnl, wx.ID_ANY, u"Reset")
szmain.Add(self.color_options, 0, wx.ALL|wx.EXPAND, 4)
szmain.Add(self.reset_button, 0, wx.ALL|wx.EXPAND, 4)
pnl.SetSizer(szmain)
self.reset_button.Bind( wx.EVT_BUTTON, self.OnResetButton )
def OnResetButton(self, event):
val = '-- Select --' # NOT WORKING
# val = ' ' # THIS WORKS, BUT RESETS TO EMPTY CHOICE
self.color_options.SetLabel(val)
app = wx.App(0)
MyFrame1(None).Show()
app.MainLoop()

updating either a static text or textctrl *read only* upon selection of an item in a choice box

Basically, what I'm trying to do is get either a static label or read only textctrl to change it's price accordingly with the item selected in the choice widget. the lists for the Item_ID's and respective prices share the same indexes despite being on 2 different lists given their simultaneous creation... thing is no matter what Item I select, the price remains the same either way Code above has the static text method... the read only textctrl turned out to be the same any ideas on what can be done?
the code of the dialog in question
class AddItemOrder ( wx.Dialog ):
def __init__( self, parent,entryit ):
wx.Dialog.__init__ ( self, parent, id = wx.ID_ANY, title = u"Add Item", pos = wx.DefaultPosition, size = wx.Size( 285,173 ), style = wx.DEFAULT_DIALOG_STYLE )
self.entryit = entryit
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
self.ite = i.Item()
bSizer25 = wx.BoxSizer( wx.VERTICAL )
gSizer9 = wx.GridSizer( 2, 2, 0, 0 )
self.m_staticText34 = wx.StaticText( self, wx.ID_ANY, u"Item ID", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText34.Wrap( -1 )
gSizer9.Add( self.m_staticText34, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5 )
self.m_choice2Choices = []
self.create_choices(self.m_choice2Choices)
self.Item_ID = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, self.m_choice2Choices, 0 )
self.Item_ID.SetSelection( 0 )
self.Item_ID.Bind(EVT_CHOICE,self.get_index)
gSizer9.Add( self.Item_ID, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_CENTER_HORIZONTAL, 5 )
self.m_staticText17 = wx.StaticText( self, wx.ID_ANY, u"Item Price", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText17.Wrap( -1 )
gSizer9.Add( self.m_staticText17, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5 )
self.Order_Price = wx.StaticText( self, wx.ID_ANY, str(self.prices[self.Item_ID.GetSelection() ]), wx.DefaultPosition, wx.DefaultSize, 0 )
self.Order_Price.Wrap( -1 )
self.Order_Price.SetLabel(str(self.prices[self.Item_ID.GetSelection() ]))
gSizer9.Add( self.Order_Price, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5 )
self.m_staticText35 = wx.StaticText( self, wx.ID_ANY, u"Item Qty", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText35.Wrap( -1 )
gSizer9.Add( self.m_staticText35, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5 )
self.Item_Qty = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 120,-1 ), 0 )
gSizer9.Add( self.Item_Qty, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5 )
bSizer25.Add( gSizer9, 1, wx.EXPAND, 5 )
self.m_button19 = wx.Button( self, wx.ID_ANY, u"Ok", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_button19.Bind(wx.EVT_BUTTON, self.ok)
bSizer25.Add( self.m_button19, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, 5 )
self.SetSizer( bSizer25 )
self.Layout()
self.Centre( wx.BOTH )
the create choices and get index functions
def create_choices(self,event):
self.prices = []
for entry in self.ite.entries:
self.custom = entry.Item_ID
self.customPr = entry.Item_Price
self.prices.append(self.customPr)
self.m_choice2Choices.append(self.custom)
return self.m_choice2Choices
def get_index(self,event):
self.currIndex = self.Item_ID.GetSelection()
return self.currIndex
When you want to change the text shown by the statictext (presumably when the EVT_CHOICE handler in this case) then you just need to call the statictext's SetLabel method with the new text. So, something like this:
newText = str(self.prices[self.currIndex])
self.m_staticText17.SetLabel(newText)

Categories