Home > OS >  Set label font to bold without changing its size and its font
Set label font to bold without changing its size and its font

Time:12-26

I know it's possible to use another object than tk.Label but I would want to do it with tk.Label (for various reasons, I'm not allowed to do it with another object).

What I don't understand is why do the font and the size of the label change when I just set it to bold. Here is a Minimum Reproducible Example:

import tkinter as tk

# make a tkinter with two labels
window = tk.Tk()
window.title("Login")
window.geometry("300x200")

label1 = tk.Label(window, text="Username")
label1.config(font="bold")
label1.grid(row=0, column=0)
label2 = tk.Label(window, text="Password")
label2.grid(row=1, column=0)

window.mainloop()

Is there anyway to only change the label to bold and keeping its size and its font? I tried to get the font of label1 before setting it to bold so that maybe i could set the size and the font to what it was before setting it to bold, but I get that: ('font', 'font', 'Font', <string object: 'TkDefaultFont'>, 'bold') and I don't really know what to do with it.

CodePudding user response:

Thanks to @8349697 I found the answer:

import tkinter as tk
import tkinter.font as tkFont

# make a tkinter with two labels
window = tk.Tk()
window.title("Login")
window.geometry("300x200")

label1 = tk.Label(window, text="Username")
label1.grid(row=0, column=0)
font: dict[str, any] = tkFont.Font(font=label1['font']).actual()
label1.configure(font=(font['family'], font['size'], 'bold'))
label2 = tk.Label(window, text="Password")
label2.grid(row=1, column=0)

window.mainloop()
  • Related