python tkinter Can I make a widget in pixel? with text?

Viewed 125

I want to make a text widget in pixel size. But always set on font size.

Here is my code:

 import tkinter as tk
 root = tk.Tk()
 test_btn = tk.Button(root, text="test", height=10, width=10)
 test_btn.pack()
 root.mainloop()

I want to use pixel, but i can't so, I am using "place" method, so my code looks dirty. I want to change them to "pixel size" and pack.

1 Answers

The width attribute is in units of characters if the button has text, but is in units of pixels if the button has an image. So, you can add a small transparent image to the button and set the compound option to allow both text and image at the same time. When you do that, width will be interpreted as pixels.

Example:

image = tk.PhotoImage(width=1, height=1)
button = tk.Button(root, image=image, text="Hello, world", compound="center",width=300)
Related