在 Tkinter 中根据用户的屏幕大小调整文本大小

Adjust text size based on user's screen size in Tkinter

我希望我的 Tkinter 应用程序的文本大小相对于用户的屏幕大小,以及其他所有已经改变的东西,比如按钮和图像,因为我已经用 .place() 制作了它们命令使用相对值。现在,我有一个糟糕的解决方案,它只适合 768p 和 1080p 用户,如果用户的屏幕更大,它就保持在 1080p。我通过创建一个“RATIO”变量来完成此操作,该变量取决于用户的屏幕尺寸和操作系统,以及我从测试中得出的非精确值。

if sys.platform == "win32":
    win, mac = True, False
    RATIO = 1
elif sys.platform == "darwin":
    from appscript import app, mactypes

    win, mac = False, True
    RATIO = 1.375

SCREEN_WIDTH, SCREEN_HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()

if SCREEN_HEIGHT != 1024:
    RATIO *= 1.4

def create_window(self, master, extra="", title=("", 0)):
    current_window = tk.Toplevel(master)

    current_window.geometry(f"{SCREEN_WIDTH}x{SCREEN_HEIGHT}+0+0")
    current_window.title(f"Background Revolution{extra}")
    self.canvas = tk.Canvas(
        current_window, width=SCREEN_WIDTH, height=SCREEN_HEIGHT, bg="#66AFF5"
    )
    
    self.title_label = tk.Label(
        self.title_frame,
        text=f"{title[0]}",
        font=("Courier", int(title[1] * RATIO)),
    )

解决方案:

# determining OS of user
# ratio is to compensate for text size differential between Windows and macOS
# every text attribute's font size should be preceded by int(RATIO * {font size})

if sys.platform == "win32":
    RATIO = 1
elif sys.platform == "darwin":
    RATIO = 1.375

1920 是我的基本情况,因为这是我正在开发的,但如果不是我的 RATIO 1.375,那是你应该调整的,因为它可能会稍微偏离。

SCREEN_WIDTH, SCREEN_HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()

RATIO *= SCREEN_WIDTH / 1920