Home > front end >  Beginner-Question: Python Tkinter Frames hiding behind small label
Beginner-Question: Python Tkinter Frames hiding behind small label

Time:01-24

I have a beginner question about python tkinter:

I've got a Frame like this:

import tkinter

root = tkinter.Tk()
root.geometry('100x100')

frame = tkinter.Frame(root, width=100, height=80, bg='green')
frame.pack()

root.mainloop()

The result is a window, thats mostly green. Now i want to place a Label on that green area. Thus I add the following between frame.pack() and root.mainloop():

label = tkinter.Label(frame, text='TESTTEST')
label.pack()

This results in a window printing TESTTEST. But nothing is green anymore. Where did my Frame go? The text isn't close to being big enough to completely cover the green area with it's own background.

What am I doing wrong? Why doesn't it work like that?

Putting another Frame between frame and label like this:

frame2 = tkinter.Frame(frame, width=100, height=20)
frame2.pack()

results in an area above the Label being colourless. However, to the left and right of my Label it's green?! Neither above nor below is any green. Just left and right of my Label.

How does this work?

CodePudding user response:

Use label.place() to specify where you want your label. eg

label.place(x=20,y=20)

this puts the label inside frame at position (20,20).

The default label width is the length of your text plus padding. You can specify width and height in place() as well along with other options.

You can specify options in your initialising statement label = tkinter.Label(frame,<*options in here>) to get background, foreground colours and other attributes.

tkinter uses default fonts so you would need to look into the font option to change that. It is possible to create your own font and apply that but I suggest you learn a bit more first before trying that.

CodePudding user response:

Widgets by default will shrink to fit their children when you use pack and grid. This is what you want 99% of the time. It may seem unintuitive and useless when making simple examples, but when creating real, complex user interfaces this makes the job easier because you don't have to worry about calculating widget sizes and placement.

If the window is configured to be larger than the frame, and if you configure the frame to fill the window, you'll see the green.

frame.pack(fill="both", expand=True)
  •  Tags:  
  • Related