在WxPython中设置框架大小?

2 投票
2 回答
6597 浏览
提问于 2025-04-18 10:15

我刚接触这个,可能有些问题很明显,抱歉。如果你看到的代码是这样的(它能正常运行):

class MainWindow(wx.Frame):
          def __init__(self, parent, title):
          self.dirname=''


          # A "-1" in the size parameter instructs wxWidgets to use the default size.
          # In this case, we select 200px width and the default height.
          wx.Frame.__init__(self, parent, title=title, size=(1000,1000))
          self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
          self.CreateStatusBar() # A Statusbar in the bottom of the window

          # Setting up the menu.
          filemenu= wx.Menu()
          menuOpen = filemenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
          menuAbout= filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
          menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")

          # Creating the menubar.
          menuBar = wx.MenuBar()
          menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
          self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.

          # Events.
          self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
          self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
          self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)

          self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
          self.buttons = []
          for i in range(0, 6):
              self.buttons.append(wx.Button(self, -1, "Button &"+str(i)))
              self.sizer2.Add(self.buttons[i], 1, wx.EXPAND)

          # Use some sizers to see layout options
          self.sizer = wx.BoxSizer(wx.VERTICAL)
          self.sizer.Add(self.control, 1, wx.EXPAND)
          self.sizer.Add(self.sizer2, 0, wx.EXPAND)

          #Layout sizers
          self.SetSizer(self.sizer)
          self.SetAutoLayout(1)
          self.sizer.Fit(self)
          self.Show()

我以为只要在 wx.Frame 的 init 里改一下 "size = " 的值就可以了,但我一改就没反应。那我该怎么改变窗口的大小呢?

另外,我怎么才能告诉窗口在屏幕上的哪个位置打开呢?谢谢!

2 个回答

1

问题其实在于你调用了self.sizer.Fit这个方法。这个Fit方法的作用是让wxPython把控件放在尽可能小的空间里,同时又能显示所有的控件。我很少使用这个方法,因为它并不总是按照我想的那样工作。你可以把这一行注释掉,然后把大小设置成你想要的任何值。

要设置窗口的位置,你需要调用SetPosition方法,并传入一组屏幕坐标。记得在显示窗口之前调用SetPosition,因为如果窗口先出现在一个地方,然后又跳到另一个地方,会显得很奇怪。

1

我觉得那些调整大小的东西正在改变你窗口的大小——毕竟它们就是这么工作的。把

self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)

后面的所有代码注释掉,看看你能不能通过初始化方法来改变窗口的大小。

撰写回答