如何使用tkinter将标签放入框架中?

2024-04-25 22:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建两个帧,并将两个标签放入第二个帧中。这是我的代码:

import tkinter as tk

root = tk.Tk()
root.geometry("500x500")

f1 = tk.Frame(root, bg = "red", width = 400, height = 250)
f2 = tk.Frame(root, bg = "blue", width = 400, height = 150)

f1.pack()
f2.pack()

text1 = tk.Label(f2, text = "lala")
text1.pack(side='left')

text2 = tk.Label(f2, text = "lalala")
text2.pack(side= "right")

root.mainloop()

为什么f2的背景色和侧面设置都不起作用

当我运行代码时,它如下所示:

enter image description here

我希望它看起来像这样:

enter image description here

多谢各位


Tags: 代码textrootwidthframesidelabelpack
1条回答
网友
1楼 · 发布于 2024-04-25 22:19:55

下面是添加了f2.pack_propagate(0)的示例,再加上添加了锚关键字以更紧密地匹配上面的示例输出(感谢acw1668

import tkinter as tk

root = tk.Tk()
root.geometry("500x500")

f1 = tk.Frame(root, bg = "red", width = 400, height = 250)
f2 = tk.Frame(root, bg = "blue", width = 400, height = 150)

f1.pack()
f2.pack()
f2.pack_propagate(0)

text1 = tk.Label(f2, bg='blue', text = "lala")
text1.pack(side='left', anchor='n')

text2 = tk.Label(f2, bg='blue', text = "lalala")
text2.pack(side= "right", anchor='n')

root.mainloop()

相关问题 更多 >