如何让我的wxpython顶层窗口居中显示在桌面上?

9 投票
2 回答
7767 浏览
提问于 2025-04-16 10:14

我想让我的图形界面程序在上下和左右都居中对齐。

wx.Frame.__init__(self, parent=None, id= -1, title="Test Frame", pos=(-1, -1), size=(1280, 770), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)

除了计算绝对位置之外,我应该怎么做才能把pos=(-1, -1)设置为居中显示(无论是800 * 600还是1280 * 800等),或者还需要设置其他属性吗?

2 个回答

6
w = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

pos=(w/2, h/2)

这段代码可以让你找到屏幕的中心位置。

现在,假设你的应用程序大小是800x600像素:

APPWIDTH = 800
APPHEIGHT = 600

w = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

# Centre of the screen
x = w / 2
y = h / 2

# Minus application offset
x -= (APPWIDTH / 2)
y -= (APPHEIGHT / 2)

pos=(x, y)
20

简单来说,直接使用

self.Center()

在类的 __init__() 方法里,替换掉 pos=(-1,-1)

撰写回答