gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:32 25 4
gpt4 key购买 nike

我正在尝试在我的 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 看起来像这样。

enter image description here

我想创建一个正方形 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()

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

Example image

希望对您有所帮助。

关于python - 如何在 wxPython 中使用 StaticBox 创建方形 LED 形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57783524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com