i am making app that will interact whit MySQL databases, to one table to bee precise. I create main frame, and 3 more, one to show table, one to insert data, and one to delete row using id key. When i start index.py all 3 scripts run, and then main window. I want to user call scripts from menu.
Here is the script:
import wx
from main import SetupGrid
from insert import InsertData
from delete import DeleteData
class GlavniProzor(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Editor Tabele Setup", size = (800,600))
self.createMenu()
self.CenterOnScreen()
self.Show()
def createMenu(self):
''' Traka menija '''
menubar = wx.MenuBar()
self.SetMenuBar(menubar)
''' Meni Specijalne funkcije '''
menu = wx.Menu()
menubar.Append(menu, '&Specijalne funkcije')
menuitem = wx.MenuItem(menu, wx.ID_ANY, 'Tabela')
#self.Bind(wx.EVT_MENU, self.prikazTabele, menuitem)
menu.AppendItem(menuitem)
menuitem = wx.MenuItem(menu, wx.ID_ANY, 'Unos u tabelu')
# self.Bind(wx.EVT_MENU, self.unosuTabelu, menuitem)
menu.AppendItem(menuitem)
menuitem = wx.MenuItem(menu, wx.ID_ANY, 'Brisanje iz tabele')
# self.Bind(wx.EVT_MENU, self.brisanjeizTabele, menuitem)
menu.AppendItem(menuitem)
menuitem = wx.MenuItem(menu, wx.ID_ANY, 'Izlaz')
# self.Bind(wx.EVT_MENU, self.izlaz, menuitem)
menu.AppendItem(menuitem)
def prikazTabele(self, evt):
dial = SetupGrid(self, -1)
dial.CenterOnParent()
dial.Show()
def unosuTabelu(self, evt):
dial = InsertData(self, -1)
dial.CenterOnParent()
dial.Show()
def brisanjeizTabele(self, evt):
dial = DeleteData(self, -1)
dial.CenterOnParent()
dial.Show()
def izlaz(self, evt):
exit()
app = wx.App(0)
frame = GlavniProzor(None)
app.MainLoop()
This is main.py scrip, which show table
#! /usr/bin/env python
import wx, MySQLdb, wx.lib.intctrl
import wx.grid as gridlib
ID_SETUP = 1
db = MySQLdb.connect("127.0.0.1", "user", "password", "database")
class SetupGrid(wx.Dialog):
def __init__(self, id, title='Tabela Setup'):
wx.Dialog.__init__(self, id, title, size=(1000, 300))
db = MySQLdb.connect("127.0.0.1", "root", "aaa111bbb", "mysqlsetup")
cursor = db.cursor()
def setupid():
sql = 'SELECT idSetup FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
def setupkomitent():
sql = 'SELECT idKomitent FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
def setupdrzava():
sql = 'SELECT Drzava FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
def setupprg():
sql = 'SELECT Prg FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
def setupprovajder():
sql = 'SELECT Provajder FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
def setupservername():
sql = 'SELECT ServerName FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
def setupdatabasename():
sql = 'SELECT DataBaseName FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
def setupsifarnici():
sql = 'SELECT Sifarnici FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
def setuppromena():
sql = 'SELECT Promena FROM setup'
cursor.execute(sql)
rezltat = cursor.fetchall()
rezultat2 = []
x = 0
for upis in rezltat:
for polje in upis:
users = str(polje)
rezultat2.append(users)
x += 1
return rezultat2
self.idSetup = setupid()
self.idKomitent = setupkomitent()
self.Drzava = setupdrzava()
self.Prg = setupprg()
self.Provajder = setupprovajder()
self.ServerName = setupservername()
self.DataBaseName = setupdatabasename()
self.Sifarnici = setupsifarnici()
self.Promena = setuppromena()
# Define main panel
panel = wx.Panel(self, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
# Define sizers
# Horizontal sizers
SetupTableSizer = wx.BoxSizer(wx.HORIZONTAL)
BtnSizer = wx.BoxSizer(wx.HORIZONTAL)
# Add species table widget
Setup = wx.grid.Grid(panel, -1, size=(1070, 200))
Setup.CreateGrid(9, 9)
Setup.SetColLabelValue(0, "idSetup")
Setup.SetColLabelValue(1, "idKomitent")
Setup.SetColLabelValue(2, "Drzava")
Setup.SetColLabelValue(3, "Prg")
Setup.SetColLabelValue(4, "Provajder")
Setup.SetColLabelValue(5, "ServerName")
Setup.SetColLabelValue(6, "DataBaseName")
Setup.SetColLabelValue(7, "Sifarnici")
Setup.SetColLabelValue(8, "Promena")
Setup.SetRowLabelSize(0)
for i in range(0, len(self.idSetup)):
Setup.SetCellValue(i, 0, self.idSetup[i])
for i in range(0, len(self.idKomitent)):
Setup.SetCellValue(i, 1, self.idKomitent[i])
for i in range(0, len(self.Drzava)):
Setup.SetCellValue(i, 2, self.Drzava[i])
for i in range(0, len(self.Prg)):
Setup.SetCellValue(i, 3, self.Prg[i])
for i in range(0, len(self.Provajder)):
Setup.SetCellValue(i, 4, self.Provajder[i])
for i in range(0, len(self.ServerName)):
Setup.SetCellValue(i, 5, self.ServerName[i])
for i in range(0, len(self.DataBaseName)):
Setup.SetCellValue(i, 6, self.DataBaseName[i])
for i in range(0, len(self.Sifarnici)):
Setup.SetCellValue(i, 7, self.Sifarnici[i])
for i in range(0, len(self.Promena)):
Setup.SetCellValue(i, 8, self.Promena[i])
Setup.AutoSize()
SetupTableSizer.Add(Setup, wx.ALIGN_CENTER | wx.ALL, 0)
panel.SetSizer(vbox)
self.Centre()
self.Show(True)
app = wx.App()
SetupGrid(None, -1)
app.MainLoop()
This is insert script
import wx
import MySQLdb
db = MySQLdb.connect("127.0.0.1", "user", "password", "database")
cursor = db.cursor()
class InsertData(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
panel = wx.Panel(self, -1)
panel.SetBackgroundColour('light gray')
#iconFile = "Grocery.ico"
#icon1 = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)
#self.SetIcon(icon1)
label1 = wx.StaticText(panel, -1, "idKomitent:")
label2 = wx.StaticText(panel, -1, "Drzava:")
label3 = wx.StaticText(panel, -1, "Prg:")
label4 = wx.StaticText(panel, -1, "Provajder:")
label5 = wx.StaticText(panel, -1, "ServerName:")
label6 = wx.StaticText(panel, -1, "DataBaseName:")
label7 = wx.StaticText(panel, -1, "Sifarnici:")
self.idKomitent = wx.TextCtrl(panel, -1, "")
self.Drzava = wx.TextCtrl(panel, -1, "")
self.Prg = wx.TextCtrl(panel, -1, "")
self.Provajder = wx.TextCtrl(panel, -1, "")
self.ServerName = wx.TextCtrl(panel, -1, "")
self.DataBaseName = wx.TextCtrl(panel, -1, "")
self.Sifarnici = wx.TextCtrl(panel, -1, "")
self.calc_btn = wx.Button(panel, -1, 'Insert')
self.calc_btn.Bind(wx.EVT_BUTTON, self.onEnter)
self.close = wx.Button(panel, -1, "Exit")
self.Bind(wx.EVT_BUTTON, self.OnCloseMe)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# use gridbagsizer for layout of widgets
sizer = wx.GridBagSizer(vgap=6, hgap=6)
sizer.Add(label1, pos=(0, 0))
sizer.Add(self.idKomitent, pos=(0, 2)) # row 0, column 2
sizer.Add(label2, pos=(1, 0))
sizer.Add(self.Drzava, pos=(1, 2))
sizer.Add(label3, pos=(2, 0))
sizer.Add(self.Prg, pos=(2, 2))
sizer.Add(label4, pos=(3, 0))
sizer.Add(self.Provajder, pos=(3, 2))
sizer.Add(label5, pos=(4, 0))
sizer.Add(self.ServerName, pos=(4, 2))
sizer.Add(label6, pos=(5, 0))
sizer.Add(self.DataBaseName, pos=(5, 2))
sizer.Add(label7, pos=(6, 0))
sizer.Add(self.Sifarnici, pos=(6, 2))
sizer.Add(self.calc_btn, pos=(8, 1))
sizer.Add(self.close, pos=(8, 2))
# use boxsizer to add border around sizer
border = wx.BoxSizer()
border.Add(sizer, 0, wx.ALL, 20)
panel.SetSizerAndFit(border)
self.Fit()
def onEnter(self, event):
# get the values from the input widgets
idKomitent = int(self.idKomitent.GetValue())
Drzava = str(self.Drzava.GetValue())
Prg = str(self.Prg.GetValue())
Provajder = str(self.Provajder.GetValue())
ServerName = str(self.ServerName.GetValue())
DataBaseName = str(self.DataBaseName.GetValue())
Sifarnici = str(self.Sifarnici.GetValue())
db = MySQLdb.connect("127.0.0.1", "user", "password", "database")
cursor = db.cursor()
cursor.execute("INSERT INTO setup (idKomitent, Drzava, Prg, Provajder, ServerName, DataBaseName, Sifarnici) VALUES (%s, %s, %s, %s, %s, %s, %s)", (idKomitent, Drzava, Prg, Provajder, ServerName, DataBaseName, Sifarnici))
cursor.execute("commit")
self.idKomitent.Clear()
self.Drzava.Clear()
self.Prg.Clear()
self.Provajder.Clear()
self.ServerName.Clear()
self.DataBaseName.Clear()
self.Sifarnici.Clear()
cursor.close()
def OnCloseMe(self, event):
self.Close(True)
def OnCloseWindow(self, event):
self.Destroy()
app = wx.App()
frame = InsertData(None, -1, "Tabela MySQL Setup")
frame.Show()
app.MainLoop()
And final delete script
import wx
import MySQLdb
db = MySQLdb.connect("127.0.0.1", "root", "aaa111bbb", "mysqlsetup")
cursor = db.cursor()
class DeleteData(wx.Frame):
def __init__(self):
wx.Frame.__init__(self)
panel = wx.Panel(self, -1)
panel.SetBackgroundColour('light gray')
#iconFile = "Grocery.ico"
#icon1 = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)
#self.SetIcon(icon1)
label1 = wx.StaticText(panel, -1, "idSetup:")
self.idSetup = wx.TextCtrl(panel, -1, "")
self.calc_btn = wx.Button(panel, -1, 'Delte')
self.calc_btn.Bind(wx.EVT_BUTTON, self.onEnter)
self.close = wx.Button(panel, -1, "Exit")
self.Bind(wx.EVT_BUTTON, self.OnCloseMe)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# use gridbagsizer for layout of widgets
sizer = wx.GridBagSizer(vgap=3, hgap=3)
sizer.Add(label1, pos=(0, 0))
sizer.Add(self.idSetup, pos=(0, 2)) # row 0, column 2
sizer.Add(self.calc_btn, pos=(2, 1))
sizer.Add(self.close, pos=(2, 2))
# use boxsizer to add border around sizer
border = wx.BoxSizer()
border.Add(sizer, 0, wx.ALL, 20)
panel.SetSizerAndFit(border)
self.Fit()
def onEnter(self, event):
# get the values from the input widgets
idSetup = int(self.idSetup.GetValue())
db = MySQLdb.connect("127.0.0.1", "user", "password", "database")
cursor = db.cursor()
cursor.execute("DELETE FROM setup WHERE idSetup = '%s'" % (idSetup))
cursor.execute("commit")
self.idSetup.Clear()
cursor.close()
def OnCloseMe(self, event):
self.Close(True)
def OnCloseWindow(self, event):
self.Destroy()
app = wx.App()
frame = DeleteData(None, -1, "Tabela MySQL Setup")
frame.Show()
app.MainLoop()
Where i made mistake??
I think that it might be as simple as adding:
if __name__ == "__main__":
before your app=wx.App() sections
i.e.
if __name__ == "__main__":
app = wx.App(0)
frame = GlavniProzor(None)
app.MainLoop()
Note: using the names ,index,main,insert and delete for your program names is probably a bad idea, they are in danger of being interpreted as keywords if not by python itself by anyone reading the code.
Related
How to modify the combobox in wxPython to dropdown a checklistbox so I can select the choices?
something like above. I know that ComboBox class is available and I need to inherit it add the feature of checkbox to dropdown list. But I am not getting the proper way to start with it.
Take a look at the ComboCtrl class. It allows you to provide the window that implements the combo's drop-down. There are some examples in the wxPython demo.
I haven't had the time to grind through ComboCtrl and it looks daunting.
However, an approximation of what you want can be achieved by torturing a wx.Dialog.
import wx
import wx.lib.scrolledpanel as scrolled
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "CheckBox Dialog",size=(400,250))
self.panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
self.log = wx.TextCtrl(self.panel, wx.ID_ANY, size=(350,150),style = wx.TE_MULTILINE|wx.TE_READONLY|wx.VSCROLL)
self.button = wx.Button(self.panel, label="Choose Colours")
sizer.Add(self.log, 0, wx.EXPAND | wx.ALL, 10)
sizer.Add(self.button, 0, wx.EXPAND | wx.ALL, 10)
self.panel.SetSizer(sizer)
self.Bind(wx.EVT_BUTTON, self.OnButton)
self.panel.options = ['Red','Green','Black','White','Orange','Blue','Yellow']
self.panel.selected = [0,0,0,0,0,0,0]
def OnButton(self,event):
dlg = ShowOptions(parent = self.panel)
dlg.ShowModal()
if dlg.result:
result_text = 'Selected: '
for item in range(len(dlg.result)):
if dlg.result[item]:
result_text += self.panel.options[item]+' '
self.log.AppendText(result_text+'\n\n')
self.panel.selected = dlg.result
else:
self.log.AppendText("No selection made\n\n")
dlg.Destroy()
class ShowOptions(wx.Dialog):
def __init__(self, parent):
self.options = parent.options
self.selected = parent.selected
o_str = ''
for item in self.options:
o_str = o_str+item+','
wx.Dialog.__init__(self, parent, wx.ID_ANY, "CheckBoxes", size= (400,250))
self.top_panel = wx.Panel(self,wx.ID_ANY)
self.avail_options = wx.TextCtrl(self.top_panel, wx.ID_ANY, o_str,style = wx.TE_READONLY)
self.bot_panel = wx.Panel(self,wx.ID_ANY)
self.scr_panel = scrolled.ScrolledPanel(self,wx.ID_ANY)
top_sizer = wx.BoxSizer(wx.VERTICAL)
scr_sizer = wx.BoxSizer(wx.VERTICAL)
bot_sizer = wx.BoxSizer(wx.VERTICAL)
self.items = []
for item in range(len(self.options)):
self.item = wx.CheckBox(self.scr_panel,-1,self.options[item])
self.item.SetValue(self.selected[item])
self.items.append(self.item)
self.item.Bind(wx.EVT_CHECKBOX, self.Select)
self.saveButton =wx.Button(self.bot_panel, label="Save")
self.closeButton =wx.Button(self.bot_panel, label="Cancel")
self.saveButton.Bind(wx.EVT_BUTTON, self.SaveOpt)
self.closeButton.Bind(wx.EVT_BUTTON, self.OnQuit)
self.Bind(wx.EVT_CLOSE, self.OnQuit)
top_sizer.Add(self.avail_options,0,flag=wx.EXPAND)
for item in self.items:
scr_sizer.Add(item,0)
bot_sizer.Add(self.saveButton,0,flag=wx.CENTER)
bot_sizer.Add(self.closeButton,0,flag=wx.CENTER)
self.scr_panel.SetupScrolling()
self.top_panel.SetSizer(top_sizer)
self.scr_panel.SetSizer(scr_sizer)
self.bot_panel.SetSizer(bot_sizer)
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(self.top_panel,0,flag=wx.EXPAND)
mainsizer.Add(self.scr_panel,1,flag=wx.EXPAND)
mainsizer.Add(self.bot_panel,0,flag=wx.EXPAND)
self.SetSizer(mainsizer)
self.Select(None)
self.Show()
def Select(self, event):
selection = []
for item in self.items:
x = item.GetValue()
selection.append(x)
selected_text = ''
for item in range(len(selection)):
if selection[item]:
selected_text += self.options[item]+' '
self.avail_options.SetValue(selected_text)
def OnQuit(self, event):
self.result = None
self.Destroy()
def SaveOpt(self, event):
self.result = []
for item in self.items:
x = item.GetValue()
self.result.append(x)
self.Destroy()
app = wx.App()
frame = MyFrame(None)
frame.Show()
app.MainLoop()
I created a widget using wx.ComboCtrl, as suggested by Robin Dunn.
Feel free to use it, or modify it any way you like.
You can also find a more advanced version of it on my GitHub account.
import wx
import wx.lib.mixins.listctrl
import operator
import functools
import contextlib
#contextlib.contextmanager
def asCM(function, *args, **kwargs):
"""Used to build with wxWidgets as context managers to help organize code."""
yield function(*args, **kwargs)
class CheckListCtrl(wx.ComboCtrl):
"""A wxListCtrl-like widget where each item in the drop-down list has a check box.
Modified code from: https://github.com/wxWidgets/Phoenix/blob/master/demo/ComboCtrl.py
"""
def __init__(self, parent, myId = None, initial = None, position = None, size = None, readOnly = False, **kwargs):
"""
parent (wxWindow) – Parent window (must not be None)
initial (str) – Initial selection string
readOnly (bool) - Determiens if the user can modify values in this widget
Example Input: CheckListCtrl(self)
"""
self.parent = parent
#Configure settings
style = []
if (readOnly):
style.append(wx.CB_READONLY)
#Create object
super().__init__(parent,
id = myId or wx.ID_ANY,
value = initial or "",
pos = position or wx.DefaultPosition,
size = size or wx.DefaultSize,
style = functools.reduce(operator.ior, style or (0,)))
self.popup = self.MyPopup(self, **kwargs)
def Append(self, *args, **kwargs):
self.popup.Append(*args, **kwargs)
class MyPopup(wx.ComboPopup):
"""The popup control used by CheckListCtrl."""
def __init__(self, parent, *, popupId = None, multiple = True, prefHeight = None,
image_check = None, image_uncheck = None, lazyLoad = False):
"""
multiple (bool) - Determines if the user can check multiple boxes or not
lazyLoad (bool) - Determines if when Create() is called
- If True: Waits for the first time the popup is called
- If False: Calls it during the build process
prefHeight (int) - What height you would prefer the popup box use
- If None: Will calculate what hight to use based on it's contents
- If -1: Will use the default height
"""
self.parent = parent
self.prefHeight = prefHeight
self._buildVar_myId = popupId
self._buildVar_multiple = multiple
self._buildVar_lazyLoad = lazyLoad
self._buildVar_image_check = image_check
self._buildVar_image_uncheck = image_uncheck
super().__init__()
parent.SetPopupControl(self)
def Create(self, parent):
self.checkList = self.MyListCtrl(self, parent,
myId = self._buildVar_myId,
multiple = self._buildVar_multiple,
image_check = self._buildVar_image_check,
image_uncheck = self._buildVar_image_uncheck)
return True
def Append(self, *args, **kwargs):
self.checkList.Append(*args, **kwargs)
def GetControl(self):
return self.checkList
def GetAdjustedSize(self, minWidth, prefHeight, maxHeight):
if (self.prefHeight is -1):
return super().GetAdjustedSize(minWidth, prefHeight, maxHeight)
elif (self.prefHeight is not None):
return (minWidth, min(self.prefHeight, maxHeight))
return self.checkList.GetBestSize(minWidth, prefHeight, maxHeight)
def LazyCreate(self):
return self._buildVar_lazyLoad
class MyListCtrl(wx.ListCtrl, wx.lib.mixins.listctrl.CheckListCtrlMixin):
"""Modified code from: https://github.com/wxWidgets/wxPython/blob/master/demo/CheckListCtrlMixin.py"""
def __init__(self, parent, root, *, myId = None, multiple = False, image_check = None, image_uncheck = None):
"""
multiple (bool) - Determines if the user can check multiple boxes or not
"""
self.parent = parent
#Configure settings
style = [wx.LC_LIST, wx.SIMPLE_BORDER]
if (not multiple):
style.append(wx.LC_SINGLE_SEL)
#Create object
wx.ListCtrl.__init__(self, root, id = myId or wx.ID_ANY, style = functools.reduce(operator.ior, style or (0,)))
wx.lib.mixins.listctrl.CheckListCtrlMixin.__init__(self, check_image = image_check, uncheck_image = image_uncheck)
def Append(self, value, default = False):
"""Appends the given item to the list.
value (str) - What the item will say
default (bool) - What state the check box will start out at
Example Input: Append("lorem")
Example Input: Append("lorem", default = True)
"""
n = self.GetItemCount()
self.InsertItem(n, value)
if (default):
self.CheckItem(n)
def GetBestSize(self, minWidth, prefHeight, maxHeight):
return (minWidth, min(prefHeight, maxHeight, sum(self.GetItemRect(i)[3] for i in range(self.GetItemCount())) + self.GetItemRect(0)[3]))
# this is called by the base class when an item is checked/unchecked
def OnCheckItem(self, index, state):
print(index, state)
if (__name__ == "__main__"):
class TestFrame(wx.Frame):
def __init__(self):
super().__init__(None, wx.ID_ANY, "Lorem Ipsum")
with asCM(wx.Panel, self, wx.ID_ANY) as myPanel:
with asCM(wx.BoxSizer, wx.VERTICAL) as mySizer:
with asCM(CheckListCtrl, myPanel, prefHeight = None) as myWidget:
myWidget.Append("lorem")
myWidget.Append("ipsum", default = True)
myWidget.Append("dolor")
mySizer.Add(myWidget, 0, wx.ALL, 5)
myPanel.SetSizer(mySizer)
####################################
app = wx.App(False)
frame = TestFrame()
frame.Show()
app.MainLoop()
From this question I found out how to ask the user for an input using wxPython. But how can I ask for multiple information at the same time?
Basicly I want to create a message box with three input fields under each other asking for "Name" "Surname" "Nickname". I also want to have the code really simple like:
name,surname,nick = askInfo("Name","Surname","Nickname")
It doesn't have to be wxPython but it MUST not be using Tkinter.
Build a wx.Dialog there are numerous examples out there.
import wx
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Dialog Test",size=(500,400))
self.panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
self.log = wx.TextCtrl(self.panel, wx.ID_ANY, size=(400,300),style = wx.TE_MULTILINE|wx.TE_READONLY|wx.VSCROLL)
self.button = wx.Button(self.panel, label="Click me")
sizer.Add(self.log, 0, wx.EXPAND | wx.ALL, 10)
sizer.Add(self.button, 0, wx.EXPAND | wx.ALL, 10)
self.panel.SetSizer(sizer)
self.Bind(wx.EVT_BUTTON, self.OnButton)
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()
class GetData(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, wx.ID_ANY, "Name Input", size= (650,220))
self.panel = wx.Panel(self,wx.ID_ANY)
self.lblname = wx.StaticText(self.panel, label="Name", pos=(20,20))
self.name = wx.TextCtrl(self.panel, value="", pos=(110,20), size=(500,-1))
self.lblsur = wx.StaticText(self.panel, label="Surname", pos=(20,60))
self.surname = wx.TextCtrl(self.panel, value="", pos=(110,60), size=(500,-1))
self.lblnick = wx.StaticText(self.panel, label="Nickname", pos=(20,100))
self.nickname = wx.TextCtrl(self.panel, value="", pos=(110,100), size=(500,-1))
self.saveButton =wx.Button(self.panel, label="Save", pos=(110,160))
self.closeButton =wx.Button(self.panel, 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()
frame = MyFrame(None)
frame.Show()
app.MainLoop()
Pay special attention to the result items
Working on a Python 2.7.10 program, for a password gui but it is giving the error that Application is not defined. I am not sure if there is something wrong with Class Application(Frame) or app = Application(root), because it ask for me to define Application but I don't why they would ask me.
from Tkinter import *
class Application(Frame):
def _init_(self, master):
Frame._init_(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.instruction = Label(self, text = "Enter the password")
self.instruction.grid(row = 0, column = 0, columnspan = 2, sticky = W)
self.password = Entry(self)
self.password.grid(row = 1, column = 1, sticky = W)
self.submit_button = Button(self, text = "Submit", commmand = self.reveal)
self.submit_button.grid(row = 2, column = 0, sticky = W)
self.text = Text(self, width = 35, height = 5, wrap = WORD)
self.text.grid(row = 3, column = 0, columnspan = 2, sticky = W)
def reveal(self):
content = self.password.get()
if content == "password":
message = "You have the order"
else:
message = "Access denied."
self.text.delete(0.0, END)
self.text.insert(0.0, message)
root = Tk()
root.title("Password")
root.geometry("250x150")
app= Application(root)
root.mainloop()
I've fixed your code, here it is:
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.instruction = Label(self, text = "Enter the password")
self.instruction.grid(row = 0, column = 0, columnspan = 2, sticky = W)
self.password = Entry(self)
self.password.grid(row = 1, column = 1, sticky = W)
self.submit_button = Button(self, text = "Submit", command = self.reveal)
self.submit_button.grid(row = 2, column = 0, sticky = W)
self.text = Text(self, width = 35, height = 5, wrap = WORD)
self.text.grid(row = 3, column = 0, columnspan = 2, sticky = W)
def reveal(self):
content = self.password.get()
if content == "password":
message = "You have the order"
else:
message = "Access denied."
self.text.delete(0.0, END)
self.text.insert(0.0, message)
root = Tk()
root.title("Password")
root.geometry("250x150")
app= Application(root)
root.mainloop()
Your problems were:
You used _init_ instead of __init__
Typo of "commmand" instead of "command"
Last two lines of procedure reveal in Application were incorrectly indented (logic error, not syntax or run-time)
It wasn't really clear what your question was to be honest and I just did this in Python 3.4.3 and made changes so that it should run in Python 2.7.10. I hope that helps.
Hi I have a program that runs the following way. When a user enters a number between 1-10 and hits the GO button 3 checboxes appear Left, Middle and Right. Upon the selection of only 1 checkbox a button Next appears. I disable the other ones after 1 is selected. I would like to return to the main program which checkbox was selected. How do I do this. I can do it through the Next button or through the checkbox selection. My code is below
import Tkinter as Tk
import ctypes
def setup_fc_error_message():
lines = ['fc is out of range: Please Enter a value from 1-10:']
MessageBox = ctypes.windll.user32.MessageBoxA
MessageBox(None, "\n".join(lines), 'Setup Info', 0)
def check_fc_range(fc_user):
# fc_float = si_units(fc_string_input)
# fc_float = float(fc_string_input)
fc_string_user = str(fc_user)
if (fc_user)>=1 and (fc_user<=10):
return (float(fc_user),fc_string_user)
else:
setup_fc_error_message()
return check_fc_range()
class MainWindow(Tk.Frame):
def __init__(self, parent):
Tk.Frame.__init__(self,parent)
self.parent = parent
self.parent.title('Test')
self.initialize()
def var_states_d(self):
return self.dvar
def var_states_r(self):
return self.rvar
def var_states_l(self):
return self.lvar
def cdb(self):
# print "variable is", self.dvar.get()
self.dvar_state = self.dvar.get()
# self.band_type = StringVar()
# self.band_type.set('D')
if self.dvar_state:
self.cr = Tk.Checkbutton(self.parent, text='Middle', state='disable', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.cl = Tk.Checkbutton(self.parent, text='Right', state='disable', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
self.nextbutton = Tk.Button(self.parent, text='NEXT', command= self.var_states_d)
self.nextbutton.grid(row=2,column=3)
else:
self.cr = Tk.Checkbutton(self.parent, text='Middle', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.cl = Tk.Checkbutton(self.parent, text='Right', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
self.nextbutton = Tk.Button(self.parent, text='NEXT', state='disable')
self.nextbutton.grid(row=2,column=3)
def crb(self):
# print "variable is", self.rvar.get()
self.rvar_state = self.rvar.get()
# self.band_type = StringVar()
# self.band_type.set('R')
if self.rvar_state:
self.cd = Tk.Checkbutton(self.parent, text='Left', state='disable', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.cl = Tk.Checkbutton(self.parent, text='Right', state='disable', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
self.nextbutton = Tk.Button(self.parent, text='NEXT', command= self.var_states_r)
self.nextbutton.grid(row=2,column=3)
else:
self.cd = Tk.Checkbutton(self.parent, text='Left', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.cl = Tk.Checkbutton(self.parent, text='Right', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
self.nextbutton = Tk.Button(self.parent, text='NEXT', state='disable')
self.nextbutton.grid(row=2,column=3)
def clb(self):
# print "variable is", self.lvar.get()
self.lvar_state = self.lvar.get()
# self.band_type = StringVar()
# self.band_type.set('L')
if self.lvar_state:
self.cd = Tk.Checkbutton(self.parent, text='Left', state='disable', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.cr = Tk.Checkbutton(self.parent, text='Middle', state='disable', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.nextbutton = Tk.Button(self.parent, text='NEXT', command= self.var_states_l)
self.nextbutton.grid(row=2,column=3)
else:
self.cd = Tk.Checkbutton(self.parent, text='Left', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.cr = Tk.Checkbutton(self.parent, text='Middle', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.nextbutton = Tk.Button(self.parent, text='NEXT', state='disable')
self.nextbutton.grid(row=2,column=3)
def initialize(self):
# self.frame = Tk.Frame(parent)
# self.frame.pack()
self.fc_gui = Tk.DoubleVar(self.parent)
self.fclabel1 = Tk.Label(self.parent, text = 'Please Enter a value between 1 and 10', fg = 'black', bg = 'yellow')
self.fclabel1.grid(row = 0, column = 0)
self.fcedit1 = Tk.Entry(self.parent, textvariable = self.fc_gui, bd = 5 )
self.fcedit1.grid(row = 1, column = 0)
self.fcbutton1 = Tk.Button(self.parent, text='GO', command = self.get_fc)
self.fcbutton1.grid(row = 1, column = 1)
def add_checkbox(self):
self.dvar = Tk.IntVar()
self.cd = Tk.Checkbutton(self.parent, text='Left', variable=self.dvar,command = self.cdb)
self.cd.grid(row = 2, column = 0)
self.rvar = Tk.IntVar()
self.cr = Tk.Checkbutton(self.parent, text='Middle', variable=self.rvar,command = self.crb)
self.cr.grid(row = 2, column = 1)
self.lvar = Tk.IntVar()
self.cl = Tk.Checkbutton(self.parent, text='Right', variable=self.lvar,command = self.clb)
self.cl.grid(row = 2, column = 2)
def get_fc(self):
self.fc_user = self.fc_gui.get()
if self.fc_user:
if check_fc_range(self.fc_user):
self.add_checkbox()
return self.fc_user
######################################################GUI portion ##############################################
def main():
root = Tk.Tk()
app = MainWindow(root)
fc_gui_user = app.get_fc()
app.mainloop()
if __name__ == "__main__":
main()
I cleaned up your MainWindow class removing the cdb, crb, cld functions so you only need one for each called on_toggle to make it more efficient. You'll also notice some slight changes in the add_checkbox function using lambda to pass in the value for that specific checkbutton. And since I combined the functions I did the same for the var_states function.
I left the Tk.IntVar in there as maybe you might have needed them. Although I'm not sure what you're wanting to use them for with a Checkbutton.
As for your question, you already had a method of finding out which checkbox was selected so I'm not entirely sure what you're after, but I've outlined where you can check them.
class MainWindow(Tk.Frame):
def __init__(self, parent):
Tk.Frame.__init__(self,parent)
self.parent = parent
self.parent.title('Test')
self.initialize()
self.chk_buttons = [] # List holding each checkbutton
self.var_states = [] # List holding each Invar for checkbutton
self.clicked = False # Variable to know if a checkbutton is currently selected
def get_var_states(self, i):
# Return IntVar of clicked checkbutton
return self.var_states[i]
def on_toggle(self, pos):
# print "variable is", self.dvar.get()
self.dvar_state = self.dvar.get()
# self.band_type = StringVar()
# self.band_type.set('D')
if not self.clicked:
# Changes all except clicked checkbox to disabled
# Altering state of existing widget
for i, chk_btn in enumerate(self.chk_buttons):
if i != pos:
chk_btn.configure(state='disable')
self.nextbutton = Tk.Button(self.parent, text='NEXT', command=lambda: self.get_var_states(pos))
self.nextbutton.grid(row=2,column=3)
# You can use these if statements to do something if a certain checkbutton is clicked
# Alternately you can call self.get_var_states(pos) here, instead of adding the command
# to the Next button so it runs when a checkbutton is clicked instead of when the Next button is clicked
if pos == 0: # Left
pass
if pos == 1: # Middle
pass
if pos == 2: # Right
pass
else:
# Changes all checkbox to normal
for chk_btn in self.chk_buttons:
chk_btn.configure(state='normal')
self.nextbutton = Tk.Button(self.parent, text='NEXT', state='disable')
self.nextbutton.grid(row=2,column=3)
self.clicked = not self.clicked #Changes between True and False with each click
def initialize(self):
# self.frame = Tk.Frame(parent)
# self.frame.pack()
self.fc_gui = Tk.DoubleVar(self.parent)
self.fclabel1 = Tk.Label(self.parent, text = 'Please Enter a value between 1 and 10', fg = 'black', bg = 'yellow')
self.fclabel1.grid(row = 0, column = 0)
self.fcedit1 = Tk.Entry(self.parent, textvariable = self.fc_gui, bd = 5 )
self.fcedit1.grid(row = 1, column = 0)
self.fcbutton1 = Tk.Button(self.parent, text='GO', command = self.get_fc)
self.fcbutton1.grid(row = 1, column = 1)
def add_checkbox(self):
# Added lambda function passing in a value corresponding to the index position in the list
self.dvar = Tk.IntVar()
self.cd = Tk.Checkbutton(self.parent, text='Left', variable=self.dvar,command = lambda: self.on_toggle(0))
self.cd.grid(row = 2, column = 0)
self.rvar = Tk.IntVar()
self.cr = Tk.Checkbutton(self.parent, text='Middle', variable=self.rvar,command = lambda: self.on_toggle(1))
self.cr.grid(row = 2, column = 1)
self.lvar = Tk.IntVar()
self.cl = Tk.Checkbutton(self.parent, text='Right', variable=self.lvar,command = lambda: self.on_toggle(2))
self.cl.grid(row = 2, column = 2)
self.chk_buttons = [self.cd, self.cr, self.cl] # List of checkboxes
self.var_states = [self.dvar, self.rvar, self.lvar] # List corresponding InvVar
def get_fc(self):
self.fc_user = self.fc_gui.get()
if self.fc_user:
if check_fc_range(self.fc_user):
self.add_checkbox()
return self.fc_user
I have a wxgrid inside a resizable scrollable panel. I dynamically add/hide/show rows in wxgrid. When I try to add/show more rows in wxgrid, it does not fit to the available space in panel but instead occupies a small area it had been occupying previously with a scrollbar for wxgrid.
Like this:
But after I resize the panel or frame, then it fits perfectly. Like this:
How can I make it to fit properly without needing to resize the panel?
I have tried all combinations of wx.EXPAND, wx.GROW, wx.ALL while adding grid to sizer and also tried gridobj.Layout() Nothing works. Any Ideas?
Iam using wx 3.0 with python 2.7 on windows 7
Edit:
Here's my code
controls.py
import wx
import wx.grid
import wx.combo
class SimpleGrid(wx.grid.Grid):
def __init__(self, parent):
wx.grid.Grid.__init__(self, parent, -1)
self.CreateGrid(10, 5)
for i in range(10):
self.SetRowLabelValue(i,str(i))
class ListCtrlComboPopup(wx.ListCtrl, wx.combo.ComboPopup):
def __init__(self,parent):
self.gfobj = parent
self.PostCreate(wx.PreListCtrl())
self.parent = parent
wx.combo.ComboPopup.__init__(self)
def AddItem(self, txt):
self.InsertStringItem(self.GetItemCount(), txt)
self.Select(0)
def GetSelectedItems(self):
del self.gfobj.selection[:]
current = -1
while True:
next = self.GetNextSelected(current)
if next == -1:
return
self.gfobj.selection.append(next)
current = next
def onItemSelected(self, event):
item = event.GetItem()
self.GetSelectedItems()
self.parent.draw_plot()
def onItemDeSelected(self, event):
self.GetSelectedItems()
self.parent.draw_plot()
def Init(self):
""" This is called immediately after construction finishes. You can
use self.GetCombo if needed to get to the ComboCtrl instance. """
self.value = -1
self.curitem = -1
def Create(self, parent):
""" Create the popup child control. Return True for success. """
wx.ListCtrl.Create(self, parent,
style=wx.LC_LIST|wx.SIMPLE_BORDER)
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onItemSelected)
self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.onItemDeSelected)
return True
def GetControl(self):
""" Return the widget that is to be used for the popup. """
return self
def SetStringValue(self, val):
""" Called just prior to displaying the popup, you can use it to
'select' the current item. """
idx = self.FindItem(-1, val)
if idx != wx.NOT_FOUND:
self.Select(idx)
def GetStringValue(self):
""" Return a string representation of the current item. """
a = self.GetItemText(self.value)
if self.value >= 0:
return a
return ""
def OnPopup(self):
""" Called immediately after the popup is shown. """
self.state = []
for i in range(self.GetItemCount()):
item = self.GetItem(itemId=i)
self.state.append(item.GetState())
#print self.state
wx.combo.ComboPopup.OnPopup(self)
def OnDismiss(self):
" Called when popup is dismissed. """
wx.combo.ComboPopup.OnDismiss(self)
main.py
import wx
import wx.lib.scrolledpanel
from controls import SimpleGrid
from controls import ListCtrlComboPopup
class GraphFrame(wx.Frame):
title = 'Demo: Data Trending Tool'
def __init__(self):
self.selection = []
self.displaySize = wx.DisplaySize()
wx.Frame.__init__(self, None, -1, self.title,
style = wx.DEFAULT_FRAME_STYLE,
size = (self.displaySize[0]/2, self.displaySize[1]/2))
self.containingpanel = wx.Panel(self, -1)
self.toppanel = wx.Panel(self, -1)
self.splittedwin = wx.SplitterWindow(self.containingpanel, wx.ID_ANY, style=wx.SP_3D | wx.SP_BORDER)
self.splittedwin.SetMinimumPaneSize(20)
self.gridpanel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
self.panel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
#### GRID
self.grid = SimpleGrid(self.gridpanel)
self.gridpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.gridpanelsizer.Add(self.grid, wx.GROW)
self.gridpanel.SetSizer(self.gridpanelsizer)
self.gridpanelsizer.Fit(self)
#### COMBOBOX
self.cc = wx.combo.ComboCtrl(self.toppanel, style=wx.CB_READONLY, size=(200,-1), )
self.cc.SetPopupMaxHeight(140)
popup = ListCtrlComboPopup(self)
self.cc.SetPopupControl(popup)
self.cc.SetText("--select--")
# Add some items to the listctrl
for i in range(10):
popup.AddItem(str(i))
#### SIZER FOR COMBOBOX
self.cbpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.cbpanelsizer.Add(self.cc, border = 5,flag = wx.LEFT)
self.toppanel.SetSizer(self.cbpanelsizer)
self.splittedwin.SplitHorizontally(self.gridpanel,self.panel,100)
##### SIZER FOR CONTAININGPANEL
self.cpsizer = wx.BoxSizer(wx.VERTICAL)
self.cpsizer.Add(self.splittedwin, 1, wx.EXPAND, 0)
self.containingpanel.SetSizer(self.cpsizer)
self.cpsizer.Fit(self.containingpanel)
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(self.toppanel, 0, wx.EXPAND)
mainsizer.Add(self.containingpanel, 1, wx.EXPAND)
self.SetSizerAndFit(mainsizer)
self.panel.SetAutoLayout(1)
self.panel.SetupScrolling()
self.gridpanel.SetAutoLayout(1)
self.gridpanel.SetupScrolling()
self.draw_plot()
def draw_plot(self):
for i in range(10):
if i in self.selection:
self.grid.ShowRow(i)
else:
self.grid.HideRow(i)
self.Layout()
#self.gridpanel.Layout()
if __name__ == "__main__":
app = wx.PySimpleApp()
app.frame = GraphFrame()
app.frame.Show()
app.MainLoop()
To simulate:
1. run main.py It displays a splitted window with a grid with single row in one panel.
Use the drop down to select more than one item (hold ctrl and select)
The wxgrid is cramped to one row space with a wxgrid scrollbar
Resize the panel using the splitter or resize the window. Now all the selected rows appear as required.
Finally found out!!!
With the help of This Answer, found that the problem was trying to redraw the gridpanel using gridpanel.Layout(). Instead redrawing the gridpanelsizer using gridpanelsizer.Layout() worked out!!
Updated main.py:
import wx
import wx.lib.scrolledpanel
from controls import SimpleGrid
from controls import ListCtrlComboPopup
class GraphFrame(wx.Frame):
title = 'Demo: Data Trending Tool'
def __init__(self):
self.selection = []
self.displaySize = wx.DisplaySize()
wx.Frame.__init__(self, None, -1, self.title,
style = wx.DEFAULT_FRAME_STYLE,
size = (self.displaySize[0]/2, self.displaySize[1]/2))
self.containingpanel = wx.Panel(self, -1)
self.toppanel = wx.Panel(self, -1)
self.splittedwin = wx.SplitterWindow(self.containingpanel, wx.ID_ANY, style=wx.SP_3D | wx.SP_BORDER)
self.splittedwin.SetMinimumPaneSize(20)
self.gridpanel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
self.panel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
#### GRID
self.grid = SimpleGrid(self.gridpanel)
self.gridpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.gridpanelsizer.Add(self.grid, wx.GROW)
self.gridpanel.SetSizer(self.gridpanelsizer)
self.gridpanelsizer.Fit(self)
#### COMBOBOX
self.cc = wx.combo.ComboCtrl(self.toppanel, style=wx.CB_READONLY, size=(200,-1), )
self.cc.SetPopupMaxHeight(140)
popup = ListCtrlComboPopup(self)
self.cc.SetPopupControl(popup)
self.cc.SetText("--select--")
# Add some items to the listctrl
for i in range(10):
popup.AddItem(str(i))
#### SIZER FOR COMBOBOX
self.cbpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.cbpanelsizer.Add(self.cc, border = 5,flag = wx.LEFT)
self.toppanel.SetSizer(self.cbpanelsizer)
self.splittedwin.SplitHorizontally(self.gridpanel,self.panel,100)
##### SIZER FOR CONTAININGPANEL
self.cpsizer = wx.BoxSizer(wx.VERTICAL)
self.cpsizer.Add(self.splittedwin, 1, wx.EXPAND, 0)
self.containingpanel.SetSizer(self.cpsizer)
self.cpsizer.Fit(self.containingpanel)
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(self.toppanel, 0, wx.EXPAND)
mainsizer.Add(self.containingpanel, 1, wx.EXPAND)
self.SetSizerAndFit(mainsizer)
self.panel.SetAutoLayout(1)
self.panel.SetupScrolling()
self.gridpanel.SetAutoLayout(1)
self.gridpanel.SetupScrolling()
self.draw_plot()
def draw_plot(self):
for i in range(10):
if i in self.selection:
self.grid.ShowRow(i)
else:
self.grid.HideRow(i)
#self.Layout()
self.gridpanelsizer.Layout()
if __name__ == "__main__":
app = wx.PySimpleApp()
app.frame = GraphFrame()
app.frame.Show()
app.MainLoop()
A great tool to debug this is the WIT (http://wiki.wxpython.org/Widget%20Inspection%20Tool)
With your corrected code I can get it to grow by forcing the sash position, not ideal, but it shows that the 'problem' is with the splitter.
import wx
import wx.lib.scrolledpanel
from controls import SimpleGrid
from controls import ListCtrlComboPopup
class GraphFrame(wx.Frame):
title = 'Demo: Data Trending Tool'
def __init__(self):
self.selection = []
self.displaySize = wx.DisplaySize()
wx.Frame.__init__(self, None, -1, self.title,
style = wx.DEFAULT_FRAME_STYLE,
size = (self.displaySize[0]/2, self.displaySize[1]/2))
self.containingpanel = wx.Panel(self, -1)
self.toppanel = wx.Panel(self, -1)
self.splittedwin = wx.SplitterWindow(self.containingpanel, wx.ID_ANY, style=wx.SP_3D | wx.SP_BORDER)
self.splittedwin.SetMinimumPaneSize(20)
self.gridpanel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
self.panel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
#### GRID
self.grid = SimpleGrid(self.gridpanel)
self.gridpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.gridpanelsizer.Add(self.grid, wx.GROW)
self.gridpanel.SetSizer(self.gridpanelsizer)
self.gridpanelsizer.Fit(self)
#### COMBOBOX
self.cc = wx.combo.ComboCtrl(self.toppanel, style=wx.CB_READONLY, size=(200,-1), )
self.cc.SetPopupMaxHeight(140)
popup = ListCtrlComboPopup(self)
self.cc.SetPopupControl(popup)
self.cc.SetText("--select--")
# Add some items to the listctrl
for i in range(10):
popup.AddItem(str(i))
#### SIZER FOR COMBOBOX
self.cbpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.cbpanelsizer.Add(self.cc, border = 5,flag = wx.LEFT)
self.toppanel.SetSizer(self.cbpanelsizer)
self.splittedwin.SplitHorizontally(self.gridpanel, self.panel, 50)
##### SIZER FOR CONTAININGPANEL
self.cpsizer = wx.BoxSizer(wx.VERTICAL)
self.cpsizer.Add(self.splittedwin, 1, wx.EXPAND, 0)
self.containingpanel.SetSizer(self.cpsizer)
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(self.toppanel, 0, wx.EXPAND)
mainsizer.Add(self.containingpanel, 1, wx.EXPAND)
self.SetSizer(mainsizer)
self.panel.SetupScrolling()
self.gridpanel.SetupScrolling()
self.draw_plot()
def draw_plot(self):
for i in range(10):
if i in self.selection:
self.grid.ShowRow(i)
else:
self.grid.HideRow(i)
s = self.grid.GetBestSize()
print(s)
self.splittedwin.SetSashPosition(s[1])
if __name__ == "__main__":
from wx.lib.mixins.inspection import InspectableApp
app = InspectableApp()
app.frame = GraphFrame()
app.frame.Show()
app.MainLoop()