首页 > 解决方案 > wxPython:将一个小部件添加到框架时,小部件位置不正确

问题描述

当我在 Frame 中使用一个 Button 并使用坐标定位它时,小部件无法正确显示。它占据了整个 Frame。当我将另一个按钮添加到框架时,两个按钮都正确显示。为什么是这样?

我已经在 Mac OS 10.4、Mac OS 10.12 和 Windows 10 上运行的 wxPython 上进行了尝试。每次都错误地显示一个小部件。

# This will display the buttons incorrectly
import wx

app = wx.App()
frame = wx.Frame(None, wx.ID_ANY, "Main Window")
button1 = wx.Button(frame, wx.ID_ANY, "Button 1", (50, 50))
frame.Show()
app.MainLoop()
# This will display the buttons correctly
import wx

app = wx.App()
frame = wx.Frame(None, wx.ID_ANY, "Main Window")
button1 = wx.Button(frame, wx.ID_ANY, "Button 1", (50, 50))
button2 = wx.Button(frame, wx.ID_ANY, "Button 2", (160, 50))
frame.Show()
app.MainLoop()

我希望一个按钮示例像两个按钮示例一样显示在指定位置。这是 wxPython 的错误吗?

标签: widgetpositionwxpython

解决方案


将框架视为小部件的包装器。通常一个框架将包含一个或多个Panels.
从文件: if the frame has exactly one child window, not counting the status and toolbar, this child is resized to take the entire frame client area.

A panel is a window on which controls are placed. It is usually placed within a frame. Its main feature over its parent class wx.Window is code for handling child windows and TAB traversal.

将 apanel合并到您的代码中:

import wx
app = wx.App()
frame = wx.Frame(None, wx.ID_ANY, "Window")
panel = wx.Panel(frame,wx.ID_ANY)
button1 = wx.Button(panel, wx.ID_ANY, "Button 1", pos=(50, 50))
frame.Show()
app.MainLoop()

它会表现自己。

在此处输入图像描述


推荐阅读