gpt4 book ai didi

Python/Tkinter : expanding fontsize dynamically to fill frame

转载 作者:行者123 更新时间:2023-12-03 20:36:28 28 4
gpt4 key购买 nike

我知道您可以通过以下命令让框架小部件扩展并填充它们在容器中可用的所有区域:frameName.pack(fill = 'both', expand = True)
对文本的字体大小有什么相同的作用?目前我的文本是标签小部件的一个属性。标签小部件的父级是 frameName .

我想我可以定义自己的函数来调用 labelName.config(fontsize = N)随着框架变大更新字体大小,但我不确定如何将它们关联起来。

这就是我的程序现在的样子:
这些块中的每一个都是一个框架小部件。我希望文本扩展以填充框架的某些容量,并响应窗口大小的调整。

最佳答案

我一直在试图弄清楚如何让文本在 tkinter 中自动调整大小。

让它为我工作的关键是将计算出的高度分配给自定义字体对象中的大小。像这样:self.label_font['size'] = height
完整示例:

from tkinter import font
import tkinter as tk


class SimpleGUIExample:
def __init__(self, master):
self.master = master
self.master.title("A simple Label")
self.master.bind('<Configure>', self.resize)

self.label_font = font.Font(self.master, family='Arial', size=12, weight='bold')

self.label = tk.Label(self.master, text="Simple Label Resizing!")
self.label.config(font=self.label_font)
self.label.pack(fill=tk.BOTH, expand=tk.YES)

self.close_button = tk.Button(self.master, text="Close", command=master.quit)
self.close_button.pack()

def resize(self, event):
height = self.label.winfo_height()
width = self.label.winfo_width()
height = height // 2
print('height %s' % height)
print('width %s' % width)
if height < 10 or width < 200:
height = 10
elif width < 400 and height > 20:
height = 20
elif width < 600 and height > 30:
height = 30
else:
height = 40
print('height %s' % height)

self.label_font['size'] = height
print(self.label_font.actual())


root = tk.Tk()
simple_gui = SimpleGUIExample(root)
root.mainloop()

关于Python/Tkinter : expanding fontsize dynamically to fill frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24440541/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com