简体   繁体   中英

Tkinter have 2 different font sizes on the same text

I would like to display the time inside of a tkinter frame in a stylish way, like this : 在此处输入图片说明

However I can't find any way to do this, please note the label with the time is centered on my frame. I've also tried putting 2 labels on the same grid cell but the label with hours and minutes is removed when I add the label with the seconds. Is there a way to put 2 labels in one ? or group them ?

class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, background = "black")
        self.root = parent

        self.columnconfigure(0, weight = 1, uniform = "x")
        self.columnconfigure(1, weight = 1, uniform = "x")
        self.columnconfigure(2, weight = 1, uniform = "x")
        self.rowconfigure(0, weight = 1, uniform = "x")
        self.rowconfigure(1, weight = 1, uniform = "x")

        self.HM = tk.Label(self, text = getHM(), fg = "white", bg = "black", font = LARGE_FONT)
        self.HM.grid(row = 0, column = 1, pady=10, sticky = 'nwe')

        self.S = tk.Label(self, text = getS(), fg = "white", bg = "black", font = LARGE_FONT)
        self.S.grid(row = 0, column = 1, pady=10, sticky = 'nwe')

        self.update_clock()

    def update_clock(self):
        HM = "10:20:"
        S = "45"
        self.HM.configure(text=HM)
        self.S.configure(text=S)
        self.root.after(1000, self.update_clock)

Thanks in advance ! Shraneid

Here is a working example that takes some of your code and the use of Font from tkinter to set 2 labels with one smaller size font.

import tkinter as tk
from tkinter.font import Font


class MainPage(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, background = "black")
        time_frame = tk.Frame(self)
        time_frame.grid(row=0, column=1)
        big_font = Font(family='Helvetica', size=33, weight='bold')
        small_font = Font(family='Helvetica', size=12, weight='bold')
        HM = tk.Label(time_frame, text="{} :".format(getHM()), fg="white", bg="black", font=big_font)
        HM.grid(row=0, column=0, pady=10)

        S = tk.Label(time_frame, text=getS(), fg="white", bg="black", font=small_font)
        S.grid(row=0, column=1, pady=10, sticky='s')

root = tk.Tk()

def getHM():
    return("10 : 00")

def getS():
    return("34")

MainPage(root).grid(row=0, column=0)
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM