I'm trying to display first name and last name using tkinter in python but the last name must be in bold. Since the first name vary in length, I can't use two different label and could not figure out how to calculate the length of the first name to have the last name at the right location (following the first name). Right now the code is simple but the last name is not bold!
from tkinter import Tk, Label
root = Tk()
first_name = "John"
last_name = "Doe"
name = first_name + " " + last_name
Label(root, text=name).place(x=100, y=100)
Found similar issue on the internet but could not understand the code to make it work. I don't have too much experience on Python. Any help would be appreciated.
You can create a custom Frame
widget with two Label
widgets inside:
class NameLabel(tk.Frame):
def __init__(self, master, first_name, last_name, font=('', 16), **kwargs):
frame_kwargs = {}
for opt in ('bd', 'relief', 'padx', 'pady'):
frame_kwargs[opt] = kwargs.pop(opt, None)
frame_kwargs['bg'] = kwargs.get('bg', None)
super().__init__(master, **frame_kwargs)
self._first_name = tk.Label(self, text=first_name, font=font, **kwargs)
self._first_name.pack(side='left')
self._last_name = tk.Label(self, text=last_name, font=font+('bold',), **kwargs)
self._last_name.pack(side='left')
Then use this custom widget to show the first and last name:
NameLabel(
root,
first_name=first_name,
last_name=last_name,
font=('Times', 24),
fg='red', bg='yellow',
bd=1, relief='solid',
padx=10, pady=5,
).place(x=100, y=100)
Result: