Skip to main content
 首页 » 编程设计

python之如何在 wxPython 中使用 StaticBox 创建方形 LED 形状

2024年11月01日852php

我正在尝试在我的 GUI 中创建 LED 形状。

我的示例代码是这样的。

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() 

GUI 看起来像这样。

我想创建一个正方形 LED,在正方形的中心有一个标签。

但是LED看起来不是一个完美的正方形,标签在左上角。

我该如何解决?

请您参考如下方法:

下面是一个使用 wx.Panel 作为 LED 并在内部使用 wx.StaticText 作为文本的示例。答案在于使用 Sizers。

文档: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() 

这就是你运行它时得到的结果

希望对您有所帮助。