Tkinter 自适应文本和尺寸 [英] Tkinter Adaptive text and dimensions

查看:80
本文介绍了Tkinter 自适应文本和尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 tkinter 中制作一个应用程序,其文本大小和尺寸将适应并适合较小的 PC 尺寸?例如,在其他语言中,您可以将文本大小和尺寸指定为百分比.有没有办法在python 3中做到这一点?我使用 tkinter 作为我的 gui 工具包

How can i make an app in tkinter with the text size and dimensions that will adapt to, and fit on smaller PC sizes? For example in other languages, you can specify text size and dimensions as percentages. Is there a way to do this in python 3? I'm using tkinter as my gui toolkit

推荐答案

一种解决方案是 制作主题或样式,您可以在其中应用自己设置的缩放算法.这是一个只有一个按钮的简单示例.

One solution is to make a theme or styles where you apply a scaling algorithm set by yourself. Here is a simple example with just a button.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

# Base size
normal_width = 1920
normal_height = 1080

# Get screen size
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# 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, this is bases on average percentage from
# width and height.
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
fontsize = int(14 * scale_factor)
minimum_size = 8
if fontsize < minimum_size:
    fontsize = minimum_size

# Create a style and configure for ttk.Button widget
default_style = ttk.Style()
default_style.configure('New.TButton', font=("Helvetica", fontsize))

frame = ttk.Frame(root)
button = ttk.Button(frame, text="Test", style='New.TButton')

frame.grid(column=0, row=0)
button.grid(column=0, row=0)

root.mainloop()

这取决于您使用什么类型的小部件,以及如何将其应用于您的 GUI.例如 tk.Button 不同于 ttk.Button.据我所知,ttk 小部件在原生外观方面比 tk 小部件更好,但我自己还没有测试过.

It will depend on what type of widgets you use, on how to apply this to your GUI. For example tk.Button is different than ttk.Button. From what I have understood ttk widgets are better when it comes to native appearance than the tk widgets, but I haven't tested this myself.

要将其应用于完整的 GUI,您需要查看您在 GUI 中使用的不同小部件,并查看可以在何处进行缩放.您需要调整 scale_factor 以使其看起来不错.您可以通过将 screen_width 和 screen_height 设置为您自己选择的分辨率来测试不同的屏幕尺寸".

To apply this to a complete GUI, you'd need to look into the different widgets you use in the GUI and see where you can do scaling. And you'll need to tweak the scale_factor to get it to look good. You can test out different "screen sizes" by setting screen_width and screen_height to resolution by your own choice.

这是一个样式和主题 来自 TkDocs 的教程

这篇关于Tkinter 自适应文本和尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆