如何根据窗口大小执行动态小部件字体大小



我正试图根据几何图形更改小部件的字体大小。我有两个问题。

  1. 使用bind,我尝试更改按钮的字体大小,它只适用于一个按钮。然而,当应用两个按钮时,它一开始工作,但突然程序失败,并显示警告信号:

    导入回溯文件"&";,第1024行,在_find_and_load中文件"&";,第170行,在中输入文件"&";,_get_module_lock中的第196行递归错误:超过的最大递归深度

这是我的代码:

from tkinter import *
from tkinter import ttk, filedialog
import math
root = Tk()
root.geometry('1280x720+400+200') 
lotlist_frame =LabelFrame(root,text="Test")
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):
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))
root.resizable(True,True) 
root.bind('<Configure>', resize)
root.mainloop()

##############################################

  1. 我也想更改LabelFrame txt的字体大小,但我不知道该怎么做

当您将绑定应用于根窗口时,该绑定将为每个小部件而不仅仅是根窗口触发。在绑定中,您根据小部件的大小计算字体的大小,但小部件有时是根窗口,有时是其他窗口。每次更改字体时,都会导致其他小部件更改大小,从而创建一批全新的<Configure>事件。

我认为简单的解决方案是确保resize只有在根窗口上捕捉到事件时才起作用:

def resize(e):
if e.widget == root:
... your code here ...

我也想更改LabelFrame txt的字体大小,但我不知道该怎么做。

假设你指的是tkinter。LabelFrame,您可以用与其他小部件相同的方式来完成:lotlist_frame.configure(font=("Helvetica", font_size))


尽管如此,一个更好的解决方案是使用字体对象。使用字体对象,您可以更改对象的大小,所有使用该字体的小部件都将自动更新。

这里有一个例子:

from tkinter import *
from tkinter import ttk, filedialog
from tkinter.font import Font
import math
root = Tk()
root.geometry('1280x720+400+200')
resizable_font = Font(family="Helvetica")
lotlist_frame =LabelFrame(root,text="Test", font=resizable_font)
lotlist_frame.place(relx=0,rely=0,relwidth=1,relheight=1)
btn_lotdelete=Button(lotlist_frame,text="Delete",width=10, font=resizable_font)
btn_lotdelete.place(relx=0.5,rely=0.8,relwidth=0.5,relheight=0.2)
btn_query=Button(lotlist_frame,text="Query!",width=10, font=resizable_font)
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)
resizable_font.configure(size=font_size)
root.resizable(True,True)
root.bind('<Configure>', resize)
root.mainloop()

这个示例正确地更改了所有小部件的字体,尽管最终结果不是很好,因为您使用了place,而且您对新大小的计算不是特别准确。但是,它说明了如何更改字体对象,所有使用该字体的小部件都会自动看到更改。

最新更新