I am trying to create LED shape in my GUI.
My example code is this.
import wx
class Main(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, title ="Static box test")
panel = wx.Panel(self)
self.myLED = wx.StaticBox(panel, -1, "myLED", pos = (50,50), size = (100,100))
self.myLED.SetBackgroundColour("blue")
self.myLED.SetForegroundColour("white")
if __name__ == "__main__":
app = wx.App()
frame = Main()
frame.Show()
app.MainLoop()
The GUI looks like this.
I wanted to create a square LED having a label in the center of the square.
But the LED doesn't look like a perfect square, and the label is on upper-left side.
How could I fix it?
Here is an example using a wx.Panel for the LED and a wx.StaticText inside for the text. The answer lies in the use of the Sizers.
Doc: https://wxpython.org/Phoenix/docs/html/sizers_overview.html
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import wx
class MainFrame(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.SetSize((400, 300))
# The led panel
self.ledPanel = wx.Panel(self, wx.ID_ANY)
self.__set_properties()
self.__do_layout()
def __set_properties(self):
# begin: MainFrame.__set_properties
self.SetTitle("frame")
self.ledPanel.SetMinSize((100, 100))
self.ledPanel.SetBackgroundColour(wx.Colour(50, 153, 204))
def __do_layout(self):
# main sizer which contains the ledPanel (wx.Panel)
mainSizer = wx.FlexGridSizer(1, 1, 0, 0)
# the Gridsizer is used to correctly place the label in the center (wx.StaticText)
myGridSizer = wx.GridSizer(1, 1, 0, 0)
myLabel = wx.StaticText(self.ledPanel, wx.ID_ANY, "My LED")
myLabel.SetForegroundColour(wx.Colour(255, 255, 255))
myLabel.SetFont(wx.Font(15, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Segoe UI"))
#Adds the label to the sizer:
myGridSizer.Add(myLabel, 0, wx.ALIGN_CENTER, 0)
#Sets the sizer to the panel (panel supports background color)
self.ledPanel.SetSizer(myGridSizer)
#Adds the panel to the mainSizer.
mainSizer.Add(self.ledPanel, 1, wx.ALIGN_CENTER, 0)
# Sets the mainSizer as the main frame sizer
self.SetSizer(mainSizer)
mainSizer.AddGrowableRow(0)
mainSizer.AddGrowableCol(0)
self.Layout()
# end of class MainFrame
# Class MyApp (to launch my app)
class MyApp(wx.App):
def OnInit(self):
self.frame = MainFrame(None, wx.ID_ANY, "")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
# end of class MyApp
# Main method:
if __name__ == "__main__":
app = MyApp(0)
app.MainLoop()
And this is what you will get when you run it
Hope this can help you.
Related
I've not been able to find an answer in the documentation. Say I have the following:
import wx
from wx import *
import sys
app = wx.App()
def quitProgram(*args):
sys.exit()
def restart(*args):
app.MainLoop()
xSize = 500
ySize = 300
window = wx.Frame(None, title = "My GUI", size = (xSize,ySize))
panel = wx.Panel(window)
# generic label
labelLeft = wx.StaticText(panel, label = 'some text', pos = (2,30))
# exit button
exit = wx.Button(panel, -1, label="Exit", pos = (1, 1), size=(-1,-1))
exit.Bind(wx.EVT_BUTTON, quitProgram)
# reset button
reset = wx.Button(panel, -1, label="Refresh", pos = (100,1), size=(-1,-1))
reset.Bind(wx.EVT_BUTTON, restart)
window.Show(True)
app.MainLoop()
How can I position the objects- buttons and labels- based on the size of the main window? I'd like the objects to reposition based on resizing the window.
The code posted is not clean wxPython code.
You must instantiate your Frame as a Class and use Sizers to automate positioning of your widgets.
A minimal code that reproduces your frame using Sizers is this:
import wx
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.SetSize((500, 300))
self.bt_exit = wx.Button(self, wx.ID_ANY, "exit")
self.bt_refresh = wx.Button(self, wx.ID_ANY, "refresh")
self.text_ctrl = wx.TextCtrl(self, wx.ID_ANY, "some text", style=wx.TE_MULTILINE)
self.SetTitle("My GUI")
self.bt_exit.Bind(wx.EVT_BUTTON, self.on_exit)
self.bt_refresh.Bind(wx.EVT_BUTTON, self.on_refresh)
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(self.bt_exit, 1, 0, 0)
sizer_2.Add(self.bt_refresh, 1, 0, 0)
sizer_1.Add(sizer_2, 0, wx.EXPAND, 0)
sizer_1.Add(self.text_ctrl, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
self.Layout()
def on_exit(self, evt):
self.Close()
def on_refresh(self, evt):
self.text_ctrl.Clear()
if __name__ == "__main__":
app = wx.App()
frame = MyFrame(None)
frame.Show()
app.MainLoop()
This is well explained in wxPython/Phoenyx docs. Check for example these tutorials
try:
import wx
except ImportError:
print 'Module not found'
class Frame(wx.Frame):
def __init__(parent,id ):
wx.Frame.__init__(self,parent,id,)
panel = wx.Panel(self)
button = wx.Button(panel,label = 'close',size = (50,50))
self.Bind(wx.EVT_BUTTON,self.OnCloseMe,button)
self.Bind(wx.EVT_CLOSE,self.OnCloseWindow)
def OnCloseMe(self,event):
self.Close(True)
def OncloseWindow(self,event):
self.Destroy()
if __name__ == '__main__':
app = wx.App()
frame = wx.Frame(parent = None, id =-1,title = 'Widget',size = (300,100))
frame.Show()
app.MainLoop()
Hi guys ,the code above is just to create a button in wxpython.but everytime i run the code ,only the Frame appears,no buttons or whatsoever inside,just blank.i tried to reinstall the wxpython module but no luck.
My second question is whenever i try to initialize say, title = 'widget', size= (300,100) in the frame constructor like wx.Frame.init(self,parent,id,title ='widget',size = (300,100) it does not work, i have to do it through this line:
frame = wx.Frame(parent = None, id =-1,title = 'Widget',size = (300,100))
why is that so.thaks
Here is a working code just add your events to it. Also consider using wxGlade to design graphically your gui instead of writing it:
import wx
import gettext
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.panel_1 = wx.Panel(self, wx.ID_ANY)
self.button_1 = wx.Button(self.panel_1, wx.ID_ANY, _("button_1"))
self.__set_properties()
self.__do_layout()
def __set_properties(self):
self.SetTitle(_("frame_1"))
def __do_layout(self):
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(self.button_1, 0, 0, 0)
self.panel_1.SetSizer(sizer_2)
sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
if __name__ == "__main__":
gettext.install("app")
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, wx.ID_ANY, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
I am writing a text editor using wxpython. I want to display the line & column numbers based on the position of the text pointer(when changed using keyboard or mouse), in the statusbar.
I tried to do it using the below code:
import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Editor', size=(300, 250))
self.panel = wx.Panel(self, -1)
self.multiText = wx.TextCtrl(self.panel, -1,"",size=(200, 100), style=wx.TE_MULTILINE|wx.EXPAND)
sizer = wx.BoxSizer()
sizer.Add(self.multiText, proportion=1, flag=wx.CENTER|wx.EXPAND)
self.panel.SetSizer(sizer)
self.CreateStatusBar()
self.multiText.Bind(wx.EVT_KEY_DOWN, self.updateLineCol)
self.multiText.Bind(wx.EVT_LEFT_DOWN, self.updateLineCol)
def updateLineCol(self, event):
#lineNum = len(self.multiText.GetRange( 0, self.multiText.GetInsertionPoint() ).split("\n"))
l,c = self.multiText.PositionToXY(self.multiText.GetInsertionPoint())
self.StatusBar.SetStatusText(str(l)+","+str(c), number=0)
event.Skip()
app = wx.App(False)
frame = TextFrame()
frame.Show()
app.MainLoop()
I tried the below 2 ways to achieve that:
1.) lineNum = len(self.multiText.GetRange( 0, self.multiText.GetInsertionPoint() ).split("\n"))
2.) l,c = self.multiText.PositionToXY(self.multiText.GetInsertionPoint())
But, both, always give the line & column values of previous position of the pointer instead of current.
Is there a way to display the current line & column values?
I think you just need to bind to EVT_KEY_UP instead of EVT_KEY_DOWN. That way the event handler isn't called until after you have finished typing. I also updated the content written to the statusbar to make it a bit clearer which value was which:
import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Editor', size=(300, 250))
self.panel = wx.Panel(self, -1)
self.multiText = wx.TextCtrl(self.panel, -1,"",size=(200, 100), style=wx.TE_MULTILINE|wx.EXPAND)
sizer = wx.BoxSizer()
sizer.Add(self.multiText, proportion=1, flag=wx.CENTER|wx.EXPAND)
self.panel.SetSizer(sizer)
self.CreateStatusBar()
self.multiText.Bind(wx.EVT_KEY_UP, self.updateLineCol)
self.multiText.Bind(wx.EVT_LEFT_DOWN, self.updateLineCol)
def updateLineCol(self, event):
#lineNum = len(self.multiText.GetRange( 0, self.multiText.GetInsertionPoint() ).split("\n"))
l,c = self.multiText.PositionToXY(self.multiText.GetInsertionPoint())
stat = "col=%s, row=%s" % (l,c)
self.StatusBar.SetStatusText(stat, number=0)
event.Skip()
app = wx.App(False)
frame = TextFrame()
frame.Show()
app.MainLoop()
I've created wx.Grid widget inside my frame and I want to change my type of cursor if the user is using the grid widget. I've managed to do that with wx.StockCursor and .SetCursor methods but my cursor keeps returning to standard cursor if the user moves the cursor above the intersections of cell and row borders. What is causing this?
import wx
import wx.grid as Gridw
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, 'Data selection', size=(785, 540))
self.Centre()
#------------------------------------------------------------------------------
panel = wx.Panel(self, wx.ID_ANY)
#------------------------------------------------------------------------------
self.grid = Gridw.Grid(panel)
self.grid.CreateGrid(250, 250)
self.grid.EnableDragGridSize(0)
self.grid.DisableDragColSize()
self.grid.DisableDragRowSize()
self.grid.SetColMinimalWidth(0, 100)
#------------------------------------------------------------------------------
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer_v = wx.BoxSizer(wx.VERTICAL)
sizer_v.Add(wx.Button(panel, -1, 'Button'), 1, wx.CENTER | wx.ALL, 5)
sizer.Add(self.grid, 1, wx.EXPAND, 5)
sizer.Add(sizer_v, 0)
panel.SetSizer(sizer)
#------------------------------------------------------------------------------
self.CreateStatusBar()
self.Show(True)
#------------------------------------------------------------------------------
cross_c = wx.StockCursor(wx.CURSOR_CROSS)
self.grid.SetCursor(cross_c)
if __name__ == '__main__':
app = wx.App()
frame = Frame().Show()
app.MainLoop()
Looks like the problem is related to that you've disabled grid resizing via EnableDragGridSize(0), DisableDragColSize() and DisableDragRowSize(). This can somewhat explain why you are seeing standard cursor on the cell borders.
Not sure if it'll help you since I don't know what OS are you using, but this works for me on linux:
cross_c = wx.StockCursor(wx.CURSOR_CROSS)
self.grid.GetGridWindow().SetCursor(cross_c)
One more option is to listen for EVT_MOTION and set cursor in the event listener:
self.cross_c = wx.StockCursor(wx.CURSOR_CROSS)
self.grid.GetTargetWindow().SetCursor(self.cross_c)
wx.EVT_MOTION(self.grid.GetGridWindow(), self.OnMouseMotion)
def OnMouseMotion(self, evt):
self.grid.GetTargetWindow().SetCursor(self.cross_c)
evt.Skip()
Hope that helps.
I am trying to make a window with 2 panels. One panel is just a notebook panel. The second panel contains a toolbar on top and a text control on the bottom. I want to arrange this panel in my frame using wx.aui.AuiManager.
The problem is that I get a big empty space of grey in my custom panel.
Here is my code:
import wx
import wx.aui
import images # contains toolbar icons
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
"AUI Tutorial",
size=(600,400))
self._mgr = wx.aui.AuiManager()
self._mgr.SetManagedWindow(self)
notebook = wx.aui.AuiNotebook(self)
nb_panel = TabPanel(notebook)
my_panel = MyPanel(self)
notebook.AddPage(nb_panel, "First Tab", False)
self._mgr.AddPane(notebook,
wx.aui.AuiPaneInfo().Name("notebook-content").
CenterPane().PaneBorder(False))
self._mgr.AddPane(my_panel,
wx.aui.AuiPaneInfo().Name("txtctrl-content").
CenterPane().PaneBorder(False))
self._mgr.GetPane("notebook-content").Show().Top().Layer(0).Row(0).Position(0)
self._mgr.GetPane("txtctrl-content").Show().Bottom().Layer(1).Row(0).Position(0)
self._mgr.Update()
class MyPanel(wx.Panel):
"""
My panel with a toolbar and richtextctrl
"""
def __init__(self,parent):
wx.Panel.__init__(self,parent=parent,id=wx.ID_ANY)
sizer = wx.BoxSizer(wx.VERTICAL)
toolbar = wx.ToolBar(self,-1)
toolbar.AddLabelTool(wx.ID_EXIT, '', images._rt_smiley.GetBitmap())
self.Bind(wx.EVT_TOOL, self.OnExit, id=wx.ID_EXIT)
toolbar.Realize()
sizer.Add(toolbar,proportion=0,flag=wx.ALL | wx.ALIGN_TOP)
text = ""
txtctrl = wx.TextCtrl(self,-1, text, wx.Point(0, 0), wx.Size(150, 90),
wx.NO_BORDER | wx.TE_MULTILINE | wx.TE_READONLY|wx.HSCROLL)
sizer.Add(txtctrl,proportion=0,flag=wx.EXPAND)
self.SetSizer(sizer)
def OnExit(self,event):
self.Close()
class TabPanel(wx.Panel):
def __init__(self,parent):
wx.Panel.__init__(self,parent=parent,id=wx.ID_ANY)
sizer = wx.BoxSizer(wx.VERTICAL)
txtOne = wx.TextCtrl(self, wx.ID_ANY, "")
txtTwo = wx.TextCtrl(self, wx.ID_ANY, "")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(txtOne, 0, wx.ALL, 5)
sizer.Add(txtTwo, 0, wx.ALL, 5)
self.SetSizer(sizer)
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyFrame()
frame.Show()
app.MainLoop()
So, how do I fix my code so that I don't have that grey block taking up MyPanel? Also, my toolbar button doesn't seem to run self.OnExit(). Why is that?
Thank you for your help.
Take out the line:
self._mgr.GetPane("notebook-content").Show().Top().Layer(0).Row(0).Position(0)
As for the OnExit() handler, it is firing!
If you want to exit the application, replace it with app.Exit()