如何在wxPython中动态定位元素

时间:2018-05-06 03:03:42

标签: python python-3.x wxpython

我在文档中找不到答案。说我有以下内容:

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

如何根据主窗口的大小定位对象按钮和标签?我希望根据调整窗口大小来重新定位对象。

1 个答案:

答案 0 :(得分:0)

发布的代码不是干净的wxPython代码 您必须将Frame实例化为类,并使用Sizer自动定位窗口小部件 使用Sizer再现帧的最小代码是:

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

在wxPython / Phoenyx文档中对此进行了详细解释。检查例如these tutorials