如何获取wxpython面板的大小

How to get the size of the wxpython panel

我正在开发日历应用程序 顶层 window 是一个框架,其中包含一个显示日历网格的面板和一个包含“关闭”按钮的面板。 我无法获得日历网格面板的大小。 当我添加代码来获取面板尺寸时,结果是 (20,20),这不可能是正确的 屏幕尺寸是 (1920,1080) 所以我期待的是 (1920, 1000) 当我添加 wx.lib.inspection 模块时,我看到显示的是正确的尺寸。它是 (1920, 968)

任何人都可以阐明如何获得正确的面板尺寸吗?

这是我目前的代码

import wx
     
class DrawFrame(wx.Frame):
  def __init__(self):
    wx.Frame.__init__(self, parent=None, title='Agenda', style= wx.CAPTION | wx.CLOSE_BOX)
    self.drawpanel = DrawPanel(self)
    self.buttonpanel = ButtonPanel(self)
    self.framesizer = wx.BoxSizer(wx.VERTICAL)
    self.framesizer.Add(self.drawpanel,1, flag=wx.EXPAND)

    # Add an empty space 10 pixels high above and below the button panel
    self.framesizer.Add((0,10),0)
    self.framesizer.Add(self.buttonpanel,0, flag=wx.EXPAND)
    self.framesizer.Add((0,10),0)
    self.SetSizer(self.framesizer)
    self.SetInitialSize()
    self.Maximize()
    self.Show()


  def GetPanelSize(self):
    return self.drawpanel.GetSize()


  def OnClose(self, event):
    self.Close()


class DrawPanel(wx.Panel):
  # This panel's parent is DrawFrame. DrawFrame is the top level window.
  def __init__(self, parent):
    wx.Panel.__init__(self, parent=parent)
    self.parent = parent
    self.Bind(wx.EVT_PAINT, self.OnPaint)
    self.x1, self.y1, self.x2, self.y2 = wx.GetClientDisplayRect()
    b = self.x1, self.y1, self.x2, self.y2 
    print b
    self.width, self.height = wx.GetDisplaySize()
    c = self.width, self.height
    print c

    
  def OnPaint(self, event=None):
    dc = wx.PaintDC(self)
    dc.Clear()
    dc.SetPen(wx.Pen(wx.BLACK, 2))
    dc.SetBrush(wx.Brush('WHITE'))

    """
    DrawRectangle (self, x, y, width, height)
    Draw a rectangle with the given corner coordinate and size.
    x and y specify the top left corner coordinates and both width and height are positive.
    """

    dc.DrawRectangle(self.x1 + 5, self.y1, self.x2 - 10, self.y2 - 60)
    dc.DrawLine(40, 100, 600, 100)


class ButtonPanel(wx.Panel):
  # This panel's parent is DrawFrame. DrawFrame is the top level window.
  def __init__(self, parent):
    wx.Panel.__init__(self, parent=parent)
    self.parent=parent
    self.buttonpanelsizer = wx.BoxSizer(wx.HORIZONTAL)
    self.closebutton = wx.Button(self, label = 'Close')
    self.Bind(wx.EVT_BUTTON, self.OnClose, self.closebutton)
    self.buttonpanelsizer.AddStretchSpacer(prop=1)
    self.buttonpanelsizer.Add(self.closebutton, 0, wx.ALIGN_CENTER)
    self.SetSizer(self.buttonpanelsizer)


  def OnClose(self, event):
    self.parent.OnClose(event)


app = wx.App(False)
frame = DrawFrame()
print frame.GetPanelSize()
app.MainLoop()

非常感谢, 谢谢

您调用 GetPanelSize 的时间过早。请记住,wxPython(以及几乎任何 GUI 框架)都是基于事件的。这意味着它要工作就必须继续处理事件,在 wxPython 的情况下意味着 app.MainLoop() 必须 运行。所以在调用 app.MainLoop() 之前不要调用 GetPanelSize。相反,在需要时调用它。你画东西的时候需要它吗?只需使用 dc.GetSize()。其他地方需要吗?处理 wx.EVT_SIZE 事件并存储当前大小。可能您必须在 EVT_SIZE 处理程序中触发一些操作。