How to plot more than once from same resource concurrency - python

I have 2 plotting buttons which takes the different datas from the same resource. Processing takes about 5 seconds. To be able press the second button in this time, I'm using wx.lib.delayedresult.
Before wx.lib.delayedresult, Pressing first button ---> processing takes 5s (during this time, i couldn't press second button) ---> RESULT 1. ---> pressing second button ---> 5s processing ---> RESULT 2. So ALL takes 10-11 seconds.
After wx.lib.delayedresult, pressing first button ---> processing takes 5s (during this time, pressing second button) ---> RESULT 1 ---> 5s ---> RESULT 2. So ALL takes 10-11 seconds.
What i want is, press first button ---> 5s processing(also press second button in this time) ---> RESULT 1 and RESULT 2. ALL should take 5-6 seconds.
Is this possible only with wx.lib.delayedresult? Or should i use thread, queue, processing etc?
Any suggestion would be greatly appreciated.
This is an small example of wx.lib.delayedresult.
from time import sleep
import wx
from wx.lib.delayedresult import startWorker
class MainWindow(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = wx.Panel(self)
self.startButton = wx.Button(self.panel, label="Long Task")
self.Button1 = wx.Button(self.panel, label="btn1")
self.Button2 = wx.Button(self.panel, label="btn2")
self.startButton.Bind(wx.EVT_BUTTON, self.OnStartButton)
self.Button1.Bind(wx.EVT_BUTTON, self.OnBtn)
self.Button2.Bind(wx.EVT_BUTTON, self.heyBtn)
self.windowSizer = wx.BoxSizer()
self.windowSizer.Add(self.panel, 1, wx.ALL | wx.EXPAND)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.startButton)
self.sizer.Add(self.Button1)
self.sizer.Add(self.Button2)
self.sizer.Add((10, 10))
self.border = wx.BoxSizer()
self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)
self.panel.SetSizerAndFit(self.border)
self.SetSizerAndFit(self.windowSizer)
self.Show()
def OnStartButton(self, e):
self.startButton.Disable()
startWorker(self.LongTaskDone, self.LongTask)
def OnBtn(self, e):
hey(self).Show()
def heyBtn(self, event):
self.Button2.Disable()
startWorker(self.LongTaskDone_2, self.LongTask)
def LongTask_2(self):
print("LT 2")
sleep(5)
def LongTaskDone_2(self, result):
self.Button2.Enable()
print("ended 2")
def LongTask(self):
print("LT 1")
sleep(5)
print("hello")
def LongTaskDone(self, result):
print("ended 1")
self.startButton.Enable()
class hey(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
app = wx.App(False)
win = MainWindow(None)
app.MainLoop()
Below, LongTask btn takes processing 5s, btn1 takes it 5s seperately. ALL together gives the result in 8-9seconds. How can i get all results in 5 seconds?
from time import sleep
import wx
import wx.lib.agw.aui as aui
from wx.lib.delayedresult import startWorker
import serial
import matplotlib.pyplot as plt
from matplotlib.pyplot import subplot
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar
import threading
class MainWindow(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__ ( self, parent )
self.panel = wx.Panel(self)
self.startButton = wx.Button(self.panel, label="Long Task")
self.Button1 = wx.Button(self.panel, label="btn1")
self.startButton.Bind(wx.EVT_BUTTON, self.OnStartButton)
self.Button1.Bind(wx.EVT_BUTTON, self.OnBtn)
self.windowSizer = wx.BoxSizer()
self.windowSizer.Add(self.panel, 1, wx.ALL|wx.EXPAND )
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.startButton)
self.sizer.Add(self.Button1)
self.sizer.Add((10, 10))
self.border = wx.BoxSizer()
self.border.Add(self.sizer, 1, wx.ALL|wx.EXPAND , 5)
#in attached file
self.x=[50144.0.... #[1]
self.y=[11.0, ... #[1]
self.z=[111.3, ... #[1]
self.panel.SetSizerAndFit(self.border)
self.SetSizerAndFit(self.windowSizer)
self.panel2 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
self.panel2.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_ACTIVECAPTION ) )
self.border.Add(self.panel2, 1, wx.ALL | wx.EXPAND, 5)
############################################ AUI windows
self._mgr = aui.AuiManager()
self._mgr.SetManagedWindow(self)
self._mgr.AddPane(self.panel, aui.AuiPaneInfo().Name("tb1").Caption("Toolbar").ToolbarPane().Right())
self._mgr.AddPane(self.panel2, aui.AuiPaneInfo().CenterPane().Caption("Sabit"))
self._mgr.SetDockSizeConstraint(0.3, 0.65) #(w,h)
self._mgr.Update()
############################################
def OnStartButton(self, e):
self.startButton.Disable()
##################################### aui-canvas
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.panel5 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer14 = wx.BoxSizer( wx.VERTICAL )
self.figure2 = Figure((5,4), 85)
self.axes2 = self.figure2.add_subplot(111)
self.canvas2 = FigureCanvas(self.panel5, -1, self.figure2)
self.toolbar2 = NavigationToolbar(self.canvas2)
self.toolbar2.Realize()
bSizer14.Add(self.canvas2, 0, wx.ALL, 5 )
bSizer14.Add(self.toolbar2, 0, wx.ALL, 5 )
self.panel5.SetSizer( bSizer14 )
self.panel5.Layout()
bSizer14.Fit( self.panel5 )
bSizer1.Add( self.panel5, 1, wx.ALL, 5 )
self._mgr.AddPane(self.panel5, aui.AuiPaneInfo().Bottom().Caption("Start"))
self._mgr.Update()
##################################### aui
startWorker(self.LongTaskDone, self.LongTask)
def OnBtn(self, e):
##################################### aui-canvas
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.panel50 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer14 = wx.BoxSizer( wx.VERTICAL )
self.figure20 = Figure((5,4), 85)
self.axes20 = self.figure20.add_subplot(111)
self.canvas20 = FigureCanvas(self.panel50, -1, self.figure20)
bSizer14.Add(self.canvas20, 0, wx.ALL, 5 )
self.panel50.SetSizer( bSizer14 )
self.panel50.Layout()
bSizer14.Fit( self.panel50 )
bSizer1.Add( self.panel50, 0, wx.ALL, 5 )
self._mgr.AddPane(self.panel50, aui.AuiPaneInfo().Bottom().Caption("Btn"))
self._mgr.Update()
##################################### aui-canvas
self.axes20.bar(self.x, self.z)
self.canvas20.draw()
def LongTask(self):
self.axes2.bar(self.x, self.y)
self.canvas2.draw()
def LongTaskDone(self, result):
print("ended 1")
self.startButton.Enable()
def thread():
thread1 = threading.Thread(target = OnStartButton)
thread2 = threading.Thread(target = OnBtn)
thread1.start()
thread2.start()
app = wx.App(False)
win = MainWindow(None)
win.Show(True)
app.MainLoop()
[1]: https://www.mediafire.com/file/yc2a52cyhvsu5hl/x-y-z.txt/file

Related

wxPython How to make a dynamic scrolled panel

I have a problem: I want to make a password manager for myself .
I have the logic for the en/decoding done and also I have the dynamic adding of passwords done, but if I add too many passwords to my manager then I can't see all of the passwords because my screen is too small.
I wanted to add a scroll bar but the scroll bar didn't work.
Even after several hours of researching the code didn't want to work. This is the code for the PanelTwo:
class PanelTwo(wx.Panel):
#staticmethod
def scale_bitmap(bitmap, width, height):
image = wx.ImageFromBitmap(bitmap)
image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)
result = wx.BitmapFromImage(image)
return result
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.refr = wx.Button(self,wx.ID_ANY,u"Refresh")
self.refr.Bind(wx.EVT_BUTTON, self.refresh)
self.co = wx.Button(self, wx.ID_ANY, u"Close")
self.co.Bind(wx.EVT_BUTTON, self.close)
self.number_of_pwds = 0
self.frame = parent
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
controlSizer = wx.BoxSizer(wx.HORIZONTAL)
self.widgetSizer = wx.BoxSizer(wx.VERTICAL)
#controlSizer.Add(self.Passest, 0, wx.CENTER | wx.ALL, 5)
controlSizer.Add(self.refr, 0, wx.CENTER | wx.ALL, 5)
controlSizer.Add(self.co, 0, wx.CENTER | wx.ALL, 5)
self.addButton = wx.Button(self, label="Add")
self.addButton.Bind(wx.EVT_BUTTON, self.onAddWidget)
controlSizer.Add(self.addButton, 0, wx.CENTER | wx.ALL, 5)
self.removeButton = wx.Button(self, label="Remove")
self.removeButton.Bind(wx.EVT_BUTTON, self.onRemoveWidget)
controlSizer.Add(self.removeButton, 0, wx.CENTER | wx.ALL, 5)
self.mainSizer.Add(controlSizer, 0, wx.CENTER)
self.mainSizer.Add(self.widgetSizer, 0, wx.CENTER | wx.ALL, 10)
self.SetSizer(self.mainSizer)
The adding and removing of the Pwds is here :
def onAddWidget(self, event):
self.number_of_pwds += 1
label = "Pwd %s" % self.number_of_pwds
name = "Pwd%s" % self.number_of_pwds
new_Text = wx.StaticText(self, label=label, name=name)
self.widgetSizer.Add(new_Text, 0, wx.ALL, 5)
self.frame.fSizer.Layout()
self.frame.Fit()
def onRemoveWidget(self, event):
if self.widgetSizer.GetChildren():
self.widgetSizer.Hide(self.number_of_pwds - 1)
self.widgetSizer.Remove(self.number_of_pwds - 1)
self.number_of_pwds -= 1
self.frame.fSizer.Layout()
self.frame.Fit()
my main Form is here :
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
"Passwort Manager",
size=(300,130))
self.panel_one = PanelOne(self)
self.panel_two = PanelTwo(self)
self.panel_three = PanelThree(self)
self.panel_two.Hide()
self.panel_three.Hide()
self.fSizer = wx.BoxSizer(wx.VERTICAL)
self.fSizer.Add(self.panel_one, 1, wx.EXPAND)
self.fSizer.Add(self.panel_two, 1, wx.EXPAND)
self.fSizer.Add(self.panel_three,1,wx.EXPAND)
self.SetSizer(self.fSizer)
self.SetBackgroundColour(Color.White)
def onSwitchPanels(self, event):
if self.panel_one.IsShown():
self.SetTitle("Passwort Manager")
self.SetBackgroundColour(Color.Random())
self.panel_one.Hide()
self.panel_two.Show()
elif self.panel_two.IsShown():
self.SetTitle("Passwort Manager")
self.SetBackgroundColour(Color.Random())
self.panel_three.Show()
self.panel_two.Hide()
else:
self.SetTitle("Passwort Manager")
self.SetBackgroundColour(Color.Random())
self.panel_one.Show()
self.panel_three.Hide()
self.Layout()
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
So how can I add a dynamic scrollbar that resizes automatically and that works with my code? I am using Python3.6.
Thanks for helping me out.
Have you tried using a scrolled panel?
import wx
import wx.lib.scrolledpanel as scrolled
class TestPanel(scrolled.ScrolledPanel):
def __init__(self, parent):
scrolled.ScrolledPanel.__init__(self, parent, -1)
"""
Write your code here...
"""
self.SetupScrolling()

wxpython : How to AppendText one by one (as any key pressed)

In this code, I have a wx TextCtrl to show information (info_window), and a function print_info() to receive texts from my main script, append them to TextCtrl. The texts are appended at the same time, but I need them to be appended like this:
hello 1
-press any key
hello 2
-press any key
hello 3
Is there any way to append the strings one by one after pressing any key by keyboard?
I suppose the key should be the function press_any_key(). It may associated with any type of wx event, but I don't know how to write the function properly.
import wx
class Frame(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.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
bSizer1 = wx.BoxSizer(wx.VERTICAL)
self.info_window = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(450,250), wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_RICH2)
bSizer1.Add(self.info_window, 0, wx.ALL, 5)
self.SetSizer(bSizer1)
self.Layout()
def print_info(self, string):
self.string = string + '\n'
self.info_window.AppendText(self.string)
self.press_any_key()
def press_any_key(self):
pass
def main():
frame.print_info('hello 1')
frame.print_info('hello 2')
frame.print_info('hello 3')
app = wx.App()
frame = Frame(None)
frame.Show()
main()
app.MainLoop()
Thanks Rolf of Saxony. I solved my problem, the key point is wx.Yield(). I modified the code as below
import wx
import time
class Frame(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.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
bSizer1 = wx.BoxSizer(wx.VERTICAL)
self.info_window = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(450,250), wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_RICH2)
bSizer1.Add(self.info_window, 0, wx.ALL, 5)
self.info_window.Bind(wx.EVT_KEY_DOWN, self.go)
self.SetSizer(bSizer1)
self.Layout()
self.go_status = False
def print_info(self, string):
self.waitkey()
self.string = string + '\n'
self.info_window.AppendText(self.string)
self.go_status = False
def go(self, event):
self.go_status = True
def waitkey(self):
while self.go_status == False:
wx.Yield()
time.sleep(0.1)
def main():
frame.print_info('hello 1')
frame.print_info('hello 2')
frame.print_info('hello 3')
app = wx.App()
frame = Frame(None)
frame.Show()
main()
app.MainLoop()
It's not pretty but I couldn't think of a easier way to do it.
import wx
import time
class Frame(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,360), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL)
self.SetSizeHints(500,360)
bSizer1 = wx.BoxSizer(wx.VERTICAL)
self.info_window = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(450,250), wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_RICH2)
self.message = wx.StaticText(self,-1,("Press any key"))
self.keyinput = wx.TextCtrl(self,-1)
bSizer1.Add(self.info_window, 0, wx.ALL, 5)
bSizer1.Add(self.message, 0, wx.ALL, 5)
bSizer1.Add(self.keyinput, 0, wx.ALL, 5)
self.SetSizer(bSizer1)
self.Layout()
self.Show()
self.keyinput.SetFocus()
def print_info(self, string):
self.WaitOnKey()
self.string = string + '\n'
self.info_window.AppendText(self.string)
def WaitOnKey(self):
while self.keyinput.GetValue() == "":
wx.Yield()
time.sleep(0.2)
self.keyinput.SetValue("")
def main():
frame.print_info('hello 1')
frame.print_info('hello 2')
frame.print_info('hello 3')
app = wx.App()
frame = Frame(None)
main()
app.MainLoop()
The code is self explanatory with the exception of wx.Yield(). This returns control back to the MainLoop which means that the program doesn't freeze. Essentially while the program waits for key input, control is passed back to the main loop every 2/10ths of a second, to see if anything else is going on. This allows the program to continue to perform normally.
Note: This will not work with function keys. For that I think you would have to find a way to bind to a key event and use event.GetKeyCode()

wxPython hide and show panel

I am creating a Python application that requires a login on start up. I want to have a main panel that will hold my login panel and on successful login the login panel will hide and the main wx.Notebook will show. The following code works, but if in the login panel I re-size the application, after I successfully login and go to the main wx.Notebook the wx.Notebook does not fit the size of the screen. If I resize again while in the main wx.Notebook the main wx.Notebook will fit the window. How do I get the main wx.Notebook to automatically re-size to the window?
Main.py
import wx
import os
from titlePanel import titlePanel
from OneLblOneCB_HorzBoxSizer_Panel import OneLblOneCB_HorzBoxSizer_Panel
from OneLblOneMultiTxt_HorzBoxSizer_Panel import OneLblOneMultiTxt_HorzBoxSizer_Panel
from OneLblOneSingleTxt_HorzBoxSizer_Panel import OneLblOneSingleTxt_HorzBoxSizer_Panel
from OneLblTxtFile_HorzBoxSizer_Panel import OneLblTxtFile_HorzBoxSizer_Panel
from OneBtn_HorzBoxSizer_Panel import OneBtn_HorzBoxSizer_Panel
from LoginPanel import LoginPanel
from ProjectsPanel import ProjectsPanel
from EvDB import EvDB
class MyFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title=title, size=(650,725))
# Create Database Tables
self.db = EvDB(self)
self.db.createTbls()
# Setting up the menu.
filemenu= wx.Menu()
ID_LOGIN = wx.NewId()
ID_LOGOUT = wx.NewId()
# wx.ID_ABOUT and wx.ID_EXIT are standard IDs provided by wxWidgets.
menuOpen = filemenu.Append(wx.ID_OPEN, "&Open"," Open and existing file")
menuAbout = filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
filemenu.AppendSeparator()
menuLogin = filemenu.Append(ID_LOGIN, 'Login')
menuLogout = filemenu.Append(ID_LOGOUT, 'Logout')
filemenu.AppendSeparator()
menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
# Set events.
self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen )
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout )
self.Bind(wx.EVT_MENU, self.OnLogin, menuLogin )
self.Bind(wx.EVT_MENU, self.OnLogout, menuLogout )
self.Bind(wx.EVT_MENU, self.OnExit, menuExit )
main = wx.Panel(self)
self.mainLogin = LoginPanel(main,-1,addSpacers=1)
self.mainLogin.Show()
# Create a notebook on the panel
self.nb = wx.Notebook(main)
self.nb.Hide()
# create the page windows as children of the notebook
flowchartPg = wx.Panel(self.nb)
entryPg = wx.ScrolledWindow(self.nb, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, style=wx.VSCROLL)
entryPg.SetScrollRate( 5, 5 )
projectsPg = ProjectsPanel(self.nb, -1)
# add the pages to the notebook with the label to show on the tab
self.nb.AddPage(projectsPg, "Projects")
self.nb.AddPage(entryPg, "Entry")
self.nb.AddPage(flowchartPg, "Flowchart")
self.entTitle = titlePanel(entryPg, -1)
self.entDescr = OneLblOneMultiTxt_HorzBoxSizer_Panel(entryPg,-1,
name="entDescr", lbl="Description")
self.srcTypeList = ['None','Website', 'Youtube', 'PDF', 'Book']
self.entSourceType = OneLblOneCB_HorzBoxSizer_Panel(entryPg,-1,
name="entSourceType", lbl="Source Type: ", cbList=self.srcTypeList, startVal='None')
self.entSource = OneLblTxtFile_HorzBoxSizer_Panel(entryPg,-1,
name="entSource", lbl="Source: ")
self.entSource.singleTxt.SetEditable(False)
self.entSource._filename.Disable()
self.entAuthor = OneLblOneSingleTxt_HorzBoxSizer_Panel(entryPg,-1,
name="entAuthor", lbl="Author: ", addSpacers=0)
self.entAuthorCre = OneLblOneMultiTxt_HorzBoxSizer_Panel(entryPg,-1,
name="entAuthorCre", lbl="Author's Credentials: ")
self.asPrjList = ['None','Project1', 'Project2', 'Project3', 'Project4']
self.entAsProject = OneLblOneCB_HorzBoxSizer_Panel(entryPg,-1,
name="asProject", lbl="Assign to Project: ", cbList=self.asPrjList, startVal='None')
self.saveOrEditList = ['New','Ev1', 'Ev2', 'Ev3', 'Ev4']
self.entSaveOrEdit = OneLblOneCB_HorzBoxSizer_Panel(entryPg,-1,
name="saveOrEdit", lbl="New or Edit: ", cbList=self.saveOrEditList, startVal='New')
self.entRemarks = OneLblOneMultiTxt_HorzBoxSizer_Panel(entryPg,-1,
name="sourceRemarks", lbl="Evidence Remarks: ")
self.entRemarks.multiTxt.SetEditable(False)
self.entAddBtn = OneBtn_HorzBoxSizer_Panel(entryPg, -1, name="entAddBtn", btn="Add")
self.entSaveBtn = OneBtn_HorzBoxSizer_Panel(entryPg, -1, name="entSaveBtn", btn="Save")
#self.loginTest = LoginPanel(entryPg, -1,addSpacers=1)
self.entSaveBtn.button.Hide()
# Bindings
self.Bind(wx.EVT_COMBOBOX, self.SourceTypeEvtComboBox, self.entSourceType.cb)
self.Bind(wx.EVT_COMBOBOX, self.AsProjectEvtComboBox, self.entAsProject.cb)
self.Bind(wx.EVT_COMBOBOX, self.SaveOrEditEvtComboBox, self.entSaveOrEdit.cb)
self.Bind(wx.EVT_BUTTON, self.EvtAddBtn, self.entAddBtn.button)
self.Bind(wx.EVT_BUTTON, self.EvtSaveBtn, self.entSaveBtn.button)
self.Bind(wx.EVT_BUTTON, self.EvtLoginBtn, self.mainLogin.loginBtns.LoginBtn)
self.Bind(wx.EVT_BUTTON, self.EvtLogoutBtn, self.mainLogin.loginBtns.LogoutBtn)
# Creating Sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
entryPgBox = wx.BoxSizer(wx.VERTICAL)
# Adding Panels to BoxSizer entry panel sizer
mainSizer.AddSpacer(10)
mainSizer.Add(self.nb, 1, wx.ALL|wx.EXPAND)
mainSizer.Add(self.mainLogin, 1, wx.ALL|wx.EXPAND)
entryPgBox.AddSpacer(20)
entryPgBox.Add(self.entAsProject, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entSaveOrEdit, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entTitle, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entDescr, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entSourceType, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entSource, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entAuthor, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entAuthorCre, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entRemarks, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
entryPgBox.Add(self.entAddBtn, 0, wx.EXPAND)
entryPgBox.Add(self.entSaveBtn, 0, wx.EXPAND)
entryPgBox.AddSpacer(10)
# Setting Layouts
entryPg.SetAutoLayout(True)
entryPg.SetSizer(entryPgBox)
entryPgBox.Fit(entryPg)
main.SetAutoLayout(True)
main.SetSizer(mainSizer)
mainSizer.Fit(main)
self.Layout()
self.Show()
def OnLogin(self,e):
self.nb.Hide()
self.mainLogin.Show()
self.Layout()
self.mainLogin.Layout()
def OnLogout(self,e):
self.mainLogin.Show()
self.nb.Hide()
self.Layout()
self.mainLogin.Layout()
def EvtLoginBtn(self,e):
self.nb.Show()
self.mainLogin.Hide()
self.Layout()
self.nb.Layout()
LoginPanel.py
class LoginPanel(wx.Panel):
def __init__(self, parent, ID, addSpacers):
wx.Panel.__init__(self, parent, ID)
sizer = wx.BoxSizer(wx.VERTICAL)
self.userNamePnl = OneLblOneSingleTxt_HorzBoxSizer_Panel(self,-1,
name="loginUser", lbl="Username: ", addSpacers=1)
self.passwordPnl = OneLblOneSingleTxt_HorzBoxSizer_Panel(self,-1,
name="loginPass", lbl="Password: ", addSpacers=1)
self.loginBtns = LoginBtnsPanel(self,-1)
if addSpacers == 1:
sizer.AddStretchSpacer()
sizer.Add(self.userNamePnl,0,wx.EXPAND)
sizer.AddSpacer(10)
sizer.Add(self.passwordPnl,0,wx.EXPAND)
sizer.AddSpacer(10)
sizer.Add(self.loginBtns,0,wx.EXPAND)
if addSpacers == 1:
sizer.AddStretchSpacer()
self.SetAutoLayout(True)
self.SetSizer(sizer)
sizer.Fit(self)
Got it! I was trying to redraw the frame with Layout(), but I needed to redraw the BoxSizer with Layout()
I added the following code to the login button:
def EvtLoginBtn(self,e):
self.nb.Show()
self.mainLogin.Hide()
self.mainSizer.Layout()
Call the Layout() method of the Frame and Panel like this
def EvtLoginBtn(self,e):
self.nb.Show()
self.mainLogin.Hide()
self.Layout()
self.nb.Layout()
The last call is probably not needed. Just check the program without it as well. The Layout() method redraws the Frame or Panel or whichever widget it is a method of.
UPDATE
Your code is obviously very big and has several other parts which I do not know. Anyways, here's something that I came up with, along the lines of the code you have provided, to show how you can do this. Hope this helps:
Main.py
import wx
from LoginPanel import LoginPanel
class MyFrame ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Something something", pos = wx.DefaultPosition, size = wx.Size( 300,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
BoxSizer0 = wx.BoxSizer( wx.VERTICAL )
# Add login panel
self.login_panel = LoginPanel(self)
BoxSizer0.Add(self.login_panel, 1, wx.EXPAND | wx.ALL, 0)
# Add notebook panel and its pages
self.nb = wx.Notebook( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )
self.nb_subpanel1 = wx.Panel( self.nb, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
self.nb.AddPage( self.nb_subpanel1, u"something", False )
self.nb_subpanel2 = wx.Panel( self.nb, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
self.nb.AddPage( self.nb_subpanel2, u"something else", False )
BoxSizer0.Add( self.nb, 1, wx.EXPAND |wx.ALL, 0 )
# Adds a logout button
self.logout_button = wx.Button( self, wx.ID_ANY, u"Logout", wx.DefaultPosition, wx.DefaultSize, 0 )
BoxSizer0.Add( self.logout_button, 0, wx.ALIGN_CENTER|wx.ALL, 5 )
# Hide nb and logout button
self.nb.Hide()
self.logout_button.Hide()
self.SetSizer( BoxSizer0 )
self.Layout()
self.Centre( wx.BOTH )
self.Show()
# Connect Events
self.logout_button.Bind( wx.EVT_BUTTON, self.on_logout )
# Virtual event handlers, override them in your derived class
def on_logout( self, event ):
self.nb.Hide()
self.logout_button.Hide()
self.login_panel.Show()
self.Layout()
if __name__ == "__main__":
app = wx.App()
MyFrame(None)
app.MainLoop()
LoginPanel.py
import wx
class LoginPanel ( wx.Panel ):
def __init__( self, parent ):
wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size = wx.Size( 300,300 ), style = wx.TAB_TRAVERSAL )
BoxSizer01 = wx.BoxSizer( wx.VERTICAL )
self.login_button = wx.Button( self, wx.ID_ANY, u"Login", wx.DefaultPosition, wx.DefaultSize, 0 )
self.login_button.SetDefault()
BoxSizer01.Add( self.login_button, 0, wx.ALIGN_CENTER|wx.ALL, 5 )
self.SetSizer( BoxSizer01 )
self.Layout()
# Connect Events
self.login_button.Bind( wx.EVT_BUTTON, self.on_login )
# Virtual event handlers, overide them in your derived class
def on_login( self, event ):
self.Hide()
self.Parent.nb.Show()
self.Parent.logout_button.Show()
self.Parent.Layout()

Splitter window issue

I am splitting a dialog box into 2 sections and using grid sizer to show list separately in section 1. I also use the length of list to create radiobox to hold three buttons. But with following script I am unable to show scroll bar to see full list of items. Any suggestions to fix it would be appreciative.
import wx
# I have following list available: lut_code
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, "Modify Hydrologic Condition", wx.DefaultPosition, wx.Size(900, 600))
splitter = wx.SplitterWindow(self, -1)
scroll1 = wx.ScrolledWindow(splitter, -1)
scroll1.SetBackgroundColour(wx.WHITE)
scroll1.SetVirtualSize(scroll1.GetBestSize() + (250,250))
scroll1.SetScrollRate(10,10)
grid_sizer = wx.GridSizer( 0, 8, 0, 0 )
self.head1 = wx.StaticText(scroll1, wx.ID_ANY, u"Code", (15,5))
self.head1.Wrap( -1 )
grid_sizer.Add( self.head1, 0, wx.ALL, 5 )
v = 0
for lu in lut_code:
v += 40
self.column11 = wx.StaticText(scroll1, wx.ID_ANY, str(lu), (15,v))
self.column11.Wrap( -1 )
grid_sizer.Add( self.column11, 0, wx.ALL, 5 )
rb = 0
radio1Choices = ['F','G','P']
for i in range(1,len(lut_code)):
rb += 40
self.radio1 = wx.RadioBox(scroll1, wx.ID_ANY, wx.EmptyString, (550,rb), (30,5), radio1Choices, 3, wx.RA_SPECIFY_COLS | wx.NO_BORDER)
self.radio1.SetSelection( 0 )
grid_sizer.Add( self.radio1, 0, wx.ALL, 5)
scroll2 = wx.ScrolledWindow(splitter,-1)
scroll2.SetBackgroundColour("light-grey")
message = """Blank"""
wx.StaticText(scroll2, -1,message, (15,150))
splitter.SplitVertically(scroll1,scroll2,-220)
def OnClose(self, event):
self.Show(False)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'splitterwindow.py')
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
you need to add in your program below scroll2 =wx.ScrolledWindow(splitter,-1)
scroll1.SetVirtualSize(scroll1.GetBestSize())
import wx
# I have following list available: lut_code
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, "Modify Hydrologic Condition", wx.DefaultPosition, wx.Size(900, 500))
splitter = wx.SplitterWindow(self, -1)
scroll1 = wx.ScrolledWindow(splitter, -1)
scroll1.SetBackgroundColour(wx.WHITE)
#scroll1.SetVirtualSize(scroll1.GetBestSize() + (250,250))
scroll1.SetScrollRate(1,1)
grid_sizer = wx.GridSizer( 0, 8, 0, 0 )
self.head1 = wx.StaticText(scroll1, wx.ID_ANY, u"Code", (15,5))
self.head1.Wrap( -1 )
grid_sizer.Add( self.head1, 0, wx.ALL, 5 )
v = 0
lut_code=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
for lu in lut_code:
v += 40
self.column11 = wx.StaticText(scroll1, wx.ID_ANY, str(lu), (15,v))
self.column11.Wrap( -1 )
grid_sizer.Add( self.column11, 0, wx.ALL, 5 )
rb = 0
radio1Choices = ['F','G','P']
for i in range(0,len(lut_code)):
rb += 40
self.radio1 = wx.RadioBox(scroll1, wx.ID_ANY, wx.EmptyString, (550,rb), (30,5), radio1Choices, 3, wx.RA_SPECIFY_COLS | wx.NO_BORDER)
self.radio1.SetSelection( 0 )
grid_sizer.Add( self.radio1, 0, wx.ALL, 5)
scroll2 =wx.ScrolledWindow(splitter,-1)
scroll1.SetVirtualSize(scroll1.GetBestSize())# + (250,250))
#wx.SetupScrolling(self, scroll_x=True, scroll_y=True, rate_x=20, rate_y=20, scrollToTop=True)
scroll2.SetBackgroundColour("light-grey")
message = """Blank"""
wx.StaticText(scroll2, -1,message, (15,150))
splitter.SplitVertically(scroll1,scroll2,-220)
def OnClose(self, event):
self.Show(False)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'splitterwindow.py')
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
output:
Set the ScrolledWindow's SetVirtualSize after adding the items, so the size can be calculated to include them.

How to add and edit time in a textctrl in wxpython?

I am developing a GUI using wxpython where i need a textctrl which selects the time .I tried with TimePickerCtrl but failed to fetch the time into the textctrl. It would be great if anyone shares a good example code which adds a time to a textctrl and can be edit the textctrl at any time.Thanks in advance.
Did you even look at the wxPython demo? It shows 3 different ways to create the picker control:
import wx
import wx.lib.masked as masked
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
# 12-hour format
text1 = wx.StaticText( self, -1, "12-hour format:", size=(150,-1))
self.time12 = masked.TimeCtrl( self, -1, name="12 hour control" )
h = self.time12.GetSize().height
spin1 = wx.SpinButton(
self, -1, wx.DefaultPosition, (-1,h), wx.SP_VERTICAL )
self.time12.BindSpinButton( spin1 )
self.addWidgets([text1, self.time12, spin1])
# 24-hour format
text2 = wx.StaticText( self, -1, "24-hour format:")
spin2 = wx.SpinButton(
self, -1, wx.DefaultPosition, (-1,h), wx.SP_VERTICAL )
self.time24 = masked.TimeCtrl(
self, -1, name="24 hour control", fmt24hr=True,
spinButton = spin2
)
self.addWidgets([text2, self.time24, spin2])
# No seconds\nor spin button
text3 = wx.StaticText( self, -1, "No seconds\nor spin button:")
self.spinless_ctrl = masked.TimeCtrl(
self, -1, name="spinless control",
display_seconds = False
)
self.addWidgets([text3, self.spinless_ctrl])
# set sizer
self.SetSizer(self.mainSizer)
def addWidgets(self, widgets):
sizer = wx.BoxSizer(wx.HORIZONTAL)
for widget in widgets:
if isinstance(widget, wx.StaticText):
sizer.Add(widget, 0, wx.ALL|wx.CENTER, 5),
else:
sizer.Add(widget, 0, wx.ALL, 5)
self.mainSizer.Add(sizer)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Spinner Demo")
panel = MyPanel(self)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
f = MyFrame()
app.MainLoop()

Categories