Why does the calculated width and height in pixel of a string in Tkinter differ between platforms?

后端 未结 3 1870
孤城傲影
孤城傲影 2020-12-01 09:33

I have a Python script which needs to calculate the exact size of arbitrary strings displayed in arbitrary fonts in order to generate simple diagrams. I can easily do it wit

3条回答
  •  遥遥无期
    2020-12-01 10:02

    After searching for ages I finally found out a way to get the width of some text in any font and size!

    from tkinter import *
    
    Window = Tk()
    Window.geometry("500x500+80+80")
    
    frame = Frame(Window) # this will hold the label
    frame.pack(side = "top")
    
    # CALCULATE:
    measure = Label(frame, font = ("Purisa", 10), text = "The width of this in pixels is.....", bg = "yellow")
    measure.grid(row = 0, column = 0) # put the label in
    measure.update_idletasks() # this is VERY important, it makes python calculate the width
    width = measure.winfo_width() # get the width
    
    # PROOF IT WORKS:
    canvas = Canvas(frame, width = 400, height = 200, bg = "light green")
    canvas.grid(row = 1, column = 0, columnspan = 100) # collumnspan is 100 so that the line lines up with the text
    line = canvas.create_line(0, 10, width, 10, width = 4) # make a line the same length as the text
    canvas.create_text(10, 20, font = ("Purisa", 10), text = "... "+str(width)+" Pixels", anchor = "nw")
    

    The line I make is proof that this works for any font.

    I have tested this for different fonts and sizes, as far as I know it works.

    This is a picture of the output: This is a picture of the output

提交回复
热议问题