Daggerpov
Daggerpov

Reputation: 384

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

I would like for my Tkinter application to have its text size relative to the user's screen size, along with everything else that already changes just fine like buttons and images, since I've made those with the .place() command using relative values. For now, I have a terrible solution which is to only accommodate 768p and 1080p users, with it staying at 1080p if the user's screen is any bigger. I've done this by creating a "RATIO" variable to depend on the user's screen size and operating system with non-exact values I've come up with from testing.

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)),
    )

Upvotes: 0

Views: 2518

Answers (1)

Daggerpov
Daggerpov

Reputation: 384

Solution:

# 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 is my base case since that's what I'm developing with but is what you should adjust, if not my RATIO of 1.375 since it could be slightly off.

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

RATIO *= SCREEN_WIDTH / 1920

Upvotes: 1

Related Questions