首页 > 解决方案 > 在 tkinter 计算器中使用窗口大小自动调整文本大小

问题描述

我一直在用 Python 3.8 开发一个 tkinter 计算器,带有基本按钮和一个输入字段。我希望按钮和输入字段中的文本自动增加(或减少)窗口的大小,与按钮本身成比例 - 尚未处理输入字段的字体大小 - 尽管尝试了一段时间,失败了。在某些尺寸下,字体会折叠到最小尺寸(参见下面的代码)或开始快速调整。当窗口移动时,它也会折叠到最小尺寸。

计算器原始尺寸

其他尺寸的计算器

# Default font size
fontsize = tkFont.Font(size=11)

def font_change(event):
    # Base size
    normal_width = 418
    normal_height = 295

    # Screen
    screen_width = event.width
    screen_height = event.height

    # Get percentage of screen size from Base size
    percentage_width = screen_width / (normal_width / 100)
    percentage_height = screen_height / (normal_height / 100)

    # Make a scaling factor
    scale_factor = ((percentage_width + percentage_height) / 2) / 100

    # Set the fontsize based on scale_factor,
    # if the fontsize is less than minimum_size
    # it is set to the minimum size
    
    # font_size is the variable to store actual size
    minimum_size = 8
    if scale_factor > minimum_size/18:
        font_size = int(18 * scale_factor)
    
    else:
        font_size = minimum_size

    fontsize.configure(size = font_size)

我将函数绑定到一个事件:

root.bind("<Configure>", font_change)

按钮示例,

decimal = Button(
    root,
    text=".",
    command=lambda: press("."),
    font = fontsize, 
    height = 2,
    width=7)
decimal.grid(row=6, column=2, sticky=NW + NE + SW + SE)

如果有人可以帮助我,将不胜感激。

标签: python-3.xtkinter

解决方案


我用两个标签构建了一个测试 GUI。 root.bind( "&LT;Configure&GT;", func )每次 root或其任何子级调整大小时都会触发。代码如下。当标签触发配置事件时,字体被最小化。再次触发配置事件,甚至更小等。

import tkinter as tk
from tkinter import font


root = tk.Tk()

root.geometry( "200x100" )

fontsize = font.Font( size = 11 )

tk.Label( root, text = 'Test', font = fontsize ).grid( padx = 5, pady = 5 )
tk.Label( root, text = 'Another Test', font = fontsize ).grid( padx = 5, pady = 5 )

def font_change(event):

    print( event.widget, event )  # See what is happening

    # Base size
    normal_width = 200
    normal_height = 100

    # Screen
    screen_width = event.width
    screen_height = event.height
    print( event.widget, event )

    
    # Get percentage of screen size from Base size
    percentage_width = screen_width / (normal_width / 100)
    percentage_height = screen_height / (normal_height / 100)

    minimum_size = 8

    # Make a scaling factor
    scale_factor = ((percentage_width + percentage_height) / 2) / 100

    # Set the fontsize based on scale_factor,
    # if the fontsize is less than minimum_size
    # it is set to the minimum size
    
    # font_size is the variable to store actual size
    
    if scale_factor > minimum_size/18:
        font_size = int(18 * scale_factor)
    
    else:
        font_size = minimum_size

    fontsize.configure( size = font_size )

root.bind( '<Configure>', font_change )

root.mainloop()

一种选择是将上述代码中的打印语句替换为

if event.widget != root:
    return None  # Jump out of the function if the widget firing configure isn't root

另一种选择是读取函数root中的宽度和高度font_change,而不是从事件中获取宽度和高度。


推荐阅读