首页 > 解决方案 > 关于 tkinter 中小部件尺寸的一些非常奇怪的问题

问题描述

我试图让一些标签的高度垂直排序,这些标签的总和是 690,以便看到所有标签都是平等的。好吧,奇怪的是,当我使用正确的代码来获取和计算它们时,这些数字是不正确的,我真的不明白这是怎么回事,为什么它给出的数字总和比 690 大得多。虽然它的意思是 690/6,因为有 6 个标签,我的主窗口的高度是 690...

所以这是我的代码:

    #Modules to import

from tkinter import*
from win32api import GetSystemMetrics

#MainWindow

root = Tk()


screen_x = int(root.winfo_screenwidth())
screen_y = int(root.winfo_screenheight())  - int(root.winfo_screenheight()) * int(9.1145833333) // 100

window_x = 512
window_y = 690 

posX = (screen_x // 2) - (window_x // 2)
posY = (screen_y // 2) - (window_y // 2)

geo = "{}x{}+{}+{}". format(window_x, window_y, posX, posY)

root.geometry(geo)
root.update()

#Widgets

l1 = Label(root, text="Red Sun", bg="red", fg="white")
l1.pack(fill=BOTH, expand=True)
l1.update()
print("_______1_______")
print(l1.winfo_width(), "x", l1.winfo_height())



l2 = Label(root, text="Green Grass", bg="green", fg="black")
l2.pack(fill=BOTH, expand=True)
l2.update()
print("_______2______")
print(l2.winfo_width(), "x", l2.winfo_height())



l3 = Label(root, text="Blue Sky", bg="blue", fg="white")
l3.pack(fill=BOTH, expand=True)
l3.update()
print("______3______")
print(l3.winfo_width(), "x", l3.winfo_height())



l4 = Label(root, text="Pink Milk", bg="pink", fg="white")
l4.pack(fill=BOTH, expand=True)
l4.update()
print("_______4_______")
print(l4.winfo_width(), "x", l4.winfo_height())



l5 = Label(root, text="Orange Apple", bg="orange", fg="white")
l5.pack(fill=BOTH, expand=True)
l5.update()
print("_______5______")
print(l5.winfo_width(), "x", l5.winfo_height())



l6 = Label(root, text="White Blood", bg="white", fg="black")
l6.pack(fill=BOTH, expand=True)
l6.update()
print("______6______")
print(l6.winfo_width(), "x", l6.winfo_height())




root.mainloop()

通常每个结果应该是 512 x 115 但我不断得到这个:

在此处输入图像描述

标签: pythonpython-3.xtkintertkinter-label

解决方案


由于您已使用.pack(fill=BOTH, expand=True)这些标签,因此它们将共享其父级的所有垂直空间:

  • 创建第一个标签时,其高度将为 690(填充父高度)
  • 创建第二个标签时,两个标签的高度各为 345(父高度的一半)
  • 创建第三个标签时,三个标签的高度各为 230(父高度的三分之一)

因此,当创建第六个标签时,六个标签的高度将分别为 115。


推荐阅读