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

如何根据窗口大小动态调整控件字体?解决递归错误及LabelFrame标题问题

问题解决方案

1. 解决<Configure>事件递归错误

递归错误是因为修改按钮字体时,按钮组件会触发自身的<Configure>事件,导致resize函数被反复调用,超出Python递归深度限制。只需在resize函数中添加判断,仅当事件由主窗口root触发时才执行字体调整:

修改后的resize函数:

def resize(e):
    # 仅响应主窗口的尺寸变化事件
    if e.widget == root:
        font_size = int((math.sqrt(pow(e.width,2)+pow(e.height,2)))/10)
        btn_query.config(font = ("Helvetica", font_size))
        btn_lotdelete.config(font = ("Helvetica", font_size))

2. 调整LabelFrame的标题字体大小

tkinter原生LabelFrame无法直接修改标题字体,需自定义一个Label作为标题,通过labelwidget属性绑定到LabelFrame上:

修改后的LabelFrame创建代码:

# 先创建自定义标题Label,设置字体
frame_title = Label(root, text="Test", font=("Helvetica", 16))  # 自定义字体和大小
lotlist_frame = LabelFrame(root, labelwidget=frame_title)
lotlist_frame.place(relx=0,rely=0,relwidth=1,relheight=1)

完整可运行代码:

from tkinter import *
from tkinter import ttk, filedialog
import math

root = Tk()
root.geometry('1280x720+400+200') 

# 自定义LabelFrame标题
frame_title = Label(root, text="Test", font=("Helvetica", 16))
lotlist_frame = LabelFrame(root, labelwidget=frame_title)
lotlist_frame.place(relx=0,rely=0,relwidth=1,relheight=1)

btn_lotdelete=Button(lotlist_frame,text="Delete",width=10)
btn_lotdelete.place(relx=0.5,rely=0.8,relwidth=0.5,relheight=0.2)

btn_query=Button(lotlist_frame,text="Query!",width=10)
btn_query.place(relx=0,rely=0.8,relwidth=0.5,relheight=0.2)

def resize(e):
    if e.widget == root:
        font_size = int((math.sqrt(pow(e.width,2)+pow(e.height,2)))/10)
        btn_query.config(font = ("Helvetica", font_size))
        btn_lotdelete.config(font = ("Helvetica", font_size))
        # 同时调整LabelFrame标题的字体大小(可选)
        frame_title.config(font=("Helvetica", font_size + 2))

root.resizable(True,True) 
root.bind('<Configure>', resize)
root.mainloop()

内容的提问来源于stack exchange,提问作者Nothinbutsoul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:20:49