简体   繁体   English

Tkinter Widget颜色不变

[英]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. 如果以前是“黑色”,则在将widget(label)放入框架内之后,颜色会再次变为白色。 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 . 您的Frame正在调整为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. 为了使Frame保持自己的尺寸而不受其子部件的影响。

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. 与其明确为框架指定宽度和高度,不如让tkinter为您做到这一点通常更好。 Fill the frame with whatever widgets you want, and let tkinter decide how big the frame should be. 用所需的小部件填充框架,然后让tkinter决定框架的大小。 Then, use appropriate options for grid or pack to arrange them logically. 然后,使用适当的grid选项或pack以逻辑方式排列它们。 When tkinter is allowed to make widgets the right size, you'll end up with a much more responsive UI. 当允许tkinter使小部件的尺寸合适时,您最终将获得响应速度更快的UI。

For example, if you set the fill and expand options when you call pack on the frame, it will not shrink to fit. 例如,如果在框架上调用pack时设置了fillexpand选项,它将不会缩小以适合。 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. 您也可以通过调用f.pack_propagate(False)来关闭“缩小以适应”功能,但这很少是正确的解决方案,因为它会迫使您计算尺寸,并且如果您在系统上运行程序,则计算可能是错误的具有不同的字体或分辨率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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