You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter中获取Frame组件的尺寸?

获取嵌套Frame的实际尺寸方法

针对不同GUI框架,都有直接获取组件尺寸的方法,以下是常见框架的实现方式:

Tkinter

使用winfo_width()和winfo_height()方法获取Frame的实际宽高,注意要在组件完成渲染后调用(避免返回0或初始设置值):

import tkinter as tk

root = tk.Tk()
outer_frame = tk.Frame(root, width=200, height=200)
outer_frame.pack()
inner_frame = tk.Frame(outer_frame, width=150, height=150)
inner_frame.pack(padx=25, pady=25)

# 延迟调用确保渲染完成
def print_frame_size():
    width = inner_frame.winfo_width()
    height = inner_frame.winfo_height()
    print(f"{width}x{height}")

root.after(100, print_frame_size)
root.mainloop()

PyQt/PySide

通过width()和height()方法获取当前尺寸,或者用size()返回的QSize对象提取数值。推荐在窗口showEvent中获取,确保布局计算完成:

from PyQt5.QtWidgets import QApplication, QFrame, QVBoxLayout, QWidget
import sys

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        outer_frame = QFrame(self)
        outer_frame.setFixedSize(200, 200)
        layout = QVBoxLayout(outer_frame)
        self.inner_frame = QFrame()
        layout.addWidget(self.inner_frame)
        self.setLayout(QVBoxLayout())
        self.layout().addWidget(outer_frame)

    def showEvent(self, event):
        super().showEvent(event)
        size_str = f"{self.inner_frame.width()}x{self.inner_frame.height()}"
        print(size_str)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

WxPython

调用GetSize()获取wx.Size对象,再用GetWidth()和GetHeight()提取具体数值,同样要在组件显示后执行:

import wx

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="Frame Size Test")
        outer_panel = wx.Panel(self)
        outer_sizer = wx.BoxSizer(wx.VERTICAL)
        self.inner_panel = wx.Panel(outer_panel)
        outer_sizer.Add(self.inner_panel, 1, wx.EXPAND | wx.ALL, 25)
        outer_panel.SetSizer(outer_sizer)
        self.SetSize(300, 300)
        self.Bind(wx.EVT_SHOW, self.on_window_show)

    def on_window_show(self, event):
        if event.IsShown():
            frame_size = self.inner_panel.GetSize()
            print(f"{frame_size.GetWidth()}x{frame_size.GetHeight()}")

if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()

关键注意事项

  • 不要在组件初始化阶段直接获取尺寸,此时布局尚未计算完成,可能返回错误值(比如0或手动设置的固定值)。
  • 若Frame由布局管理器控制大小,上述方法返回的是布局调整后的实际显示尺寸,而非初始设置值。

内容的提问来源于stack exchange,提问作者Hides - In - Barrels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:05:23