0

I am looking to set the Label Widget width to an exact value - width=100 should be 100 pixels.

Is there a way to achieve this or should I be looking at using a different widget?

When using the TKinter Label, the width and height parameters refer to the text size - height=2 will set the label large enough for two lines of text, not 2 pixels as I would expect.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

0

You can assign a blank image to the label, then you can specify width option in pixels:

import tkinter as tk

root = tk.Tk()

blank = tk.PhotoImage()
tk.Label(root, image=blank, text="Hello", width=200, height=50, compound="c", bg="yellow", bd=0, padx=0).pack(padx=100, pady=10)
tk.Label(root, image=blank, text="World", width=200, height=30, compound="c", bg="cyan", bd=0, padx=0).pack(padx=100, pady=10)

root.mainloop()

Result:

enter image description here

acw1668
  • 40,144
  • 5
  • 22
  • 34
  • If i try to update the text on the Image/Label - `labelTimer.config(text = str(gameTimer))` ...I get an error... `_tkinter.TclError: image "pyimage2" doesn't exist` If I search the error, none of the solutions seem to apply - can you shed a light on it? – Kevin Russell Dec 30 '22 at 23:04
  • @KevinRussell I cannot reproduce your issue when I try to change the text of the labels. Did you put the code inside a function? – acw1668 Dec 31 '22 at 10:15
  • Yes the root is decalred outside the function `def showScoreBatak():` ` blank = PhotoImage()` ` labelTimer = Label(root, image=blank, text='TIME REMAINING', font=("Arial", 25), fg="#000", bg="#fff", borderwidth=0, padx=103, pady=15, anchor='center', width=165, height=50, compound="c")` ` labelTimer.place(x=20, y=25)` – Kevin Russell Dec 31 '22 at 12:25
  • Then in another function `labelTimer.config(text="0")` – Kevin Russell Dec 31 '22 at 12:28
  • `blank` is garbage collected after exiting `showScoreBatak()`. Also `labelTimer` cannot be accessed outside the function because it is a local variable. – acw1668 Dec 31 '22 at 12:36
  • @KevinRussell If you use `place()` on the label, you can simply use `.place(..., width=..., height=...)` and don't need to use a blank image. – acw1668 Dec 31 '22 at 15:23