简体   繁体   中英

Tkinter Widget color does not change

When I put a widget inside the frame, the color of the frame vanishes. If it was 'black' before, then after putting a widget(label) inside the frame, the color again becomes white. Here's my code:

from tkinter import *
root = Tk()
root.geometry("700x600")
f = Frame(root, height = 400, width = 400, bg = 'black')
f.pack()
id = Label(f, text = "Email:", fg = 'blue', font = ('Kristen ITC', 18))
id.pack()

Your Frame is resizing itself to the Label . You need to set...:

...
f.pack_propagate(False)
f.pack()
...

In order for the Frame to maintain its own dimension without affected by the its children widgets.

By default, widgets shrink or expand to fit their contents. When you add the button, the frame shrinks down to fit.

It appears you want the frame to take up just a part of the root window. Instead of explicitly giving the frame a width and height, it's usually better to let tkinter do that for you. Fill the frame with whatever widgets you want, and let tkinter decide how big the frame should be. Then, use appropriate options for grid or pack to arrange them logically. When tkinter is allowed to make widgets the right size, you'll end up with a much more responsive UI.

For example, if you set the fill and expand options when you call pack on the frame, it will not shrink to fit. If you later need to add more widgets, you won't have to modify other parts of your code to make them fit.

f.pack(fill="both", expad=True)

You can also turn off this "shrink to fit" feature by calling f.pack_propagate(False) , but that is rarely the right solution because it forces you to calculate sizes, and your calculations may be wrong if you run the program on a system with different fonts or different resolutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM