Home > Blockchain >  tkinter when I set a widgets height and width the right geometry is not set
tkinter when I set a widgets height and width the right geometry is not set

Time:08-21

This is the code :

from tkinter import *

app = Tk()
app.configure(background='DimGray')

b=Button(app,bg='#e6e6e6',width=50,height=50)
b.pack()
b.update()
print(b.winfo_width())

app.mainloop()

And this is the output : 360

The output should be 50 but it is not

CodePudding user response:

The width and height parameters for a button are predicated upon whether the button has an image or text. Since neither is part of the definition of your button, it is hard to say what size the button will actually be displayed as. I took your code and added some text to the button.

from tkinter import *

app = Tk()
app.configure(background='DimGray')

b=Button(app,bg='#e6e6e6', height=1, width=20, text="Hello")
b.pack()
b.update()
print(b.winfo_width())

app.mainloop()

Then, since height and width are now predicated upon the size of the letters in the text "Hello", I set up the height to be "1" letter high and the width of the button to be "20" letters wide. When I ran this version of the program the system displayed a nominal sized button that filled the window as it was the only widget within the window.

Hello Button

The resulting width info for the window (b.winfo_width()) was 188 pixels which is the result of the letter width times a factor of "20".

Anyway, try that out to see if it clarifies things for you.

CodePudding user response:

Try to use place() method instead pack().

from tkinter import *

app = Tk()
app.configure(background='DimGray')

b=Button(app,bg='#e6e6e6')
b.place(width=50, height=50)
b.update()
print(b.winfo_width())

app.mainloop()  # Output: 50

This is because place() method uses pixels to describe widgets on the screen and pack() method uses some kind of position relative to another objects.

Also be careful, width and height of your objects must be written inside place() method!

  • Related