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

如何刷新Tkinter文本框以应用最新字体大小?

解决Tkinter文本框字体大小不更新的问题

你当前的font_size函数犯了一个关键错误——每次点击按钮时你新建了一个Text控件,但没有把它添加到界面布局里,原来的文本框依然保留着旧的字体大小,所以看不到变化。正确的做法是直接修改已存在的文本框的字体属性,而不是重新创建控件。

修改方案

  1. 在font_size函数中声明要使用的全局变量(包括文本框对象text)
  2. 删掉新建Text控件的代码,改用text.config()方法直接更新字体大小

修改后的完整代码

import re
from tkinter import *
from tkinter import ttk
import time

root = Tk()
root.title('Notepad')
root.iconbitmap('C:/Users/Hero/Documents/Visual Studio code/My project/notes.ico')
root.geometry("500x500")

root.tk.call("source", "C:/Users/Hero/Documents/Visual Studio code/My project/azure.tcl")
root.tk.call("set_theme", "dark")

x = 20

def change_theme():
    if root.tk.call("ttk::style", "theme", "use") == "azure-dark":
        root.tk.call("set_theme", "light")
    else:
        root.tk.call("set_theme", "dark")

def font_size():
    global x, text
    x = x + 1
    print(x)
    # 直接更新现有文本框的字体大小
    text.config(font=("Georgia", x))

style=ttk.Style()
style.theme_use('azure-dark')
style.configure("Vertical.TScrollbar", background="grey", bordercolor="black", arrowcolor="white")

barframe = Frame()
barframe.pack(side=BOTTOM)

fonts = ttk.Button(barframe, text='Size and Font', width=15, style='Accent.TButton', command=font_size)
calculater = ttk.Button(root, text='Calculater', width=15, style='Accent.TButton')
fonts.grid(row=0, column=0)

scroll = ttk.Scrollbar(root, orient='vertical')
scroll.pack(side=RIGHT, fill='y')

text=Text(root, font=("Georgia", x), yscrollcommand=scroll.set, bg='#292929', height=1, width=1)
scroll.config(command=text.yview)
text.pack(fill=BOTH, expand=1)

root.mainloop()

关键修改说明

  • 添加global text是为了让函数能访问到全局作用域中创建的文本框对象
  • text.config(font=("Georgia", x))会直接修改文本框的字体配置,调用后文本框会立即刷新显示新的字体大小

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:54:18