首页 > 解决方案 > 如何控制 Tkinter 网格中的标签位置和间距

问题描述

现在我想在同一行制作食品价格,因此我也将其更改为第 2 行,但输出是这样的

食物回到第 0 行,为什么会这样?我试图得到这样的东西:

foodprice=['3','2','1.50']
drinks = ['Water','Hot water','Medium water']
drinksprice = ['1','2','3']

myFrame3 = Frame(root, bg = '')
myFrame3.pack()

myFrame3.columnconfigure(0, weight=1)
myFrame3.columnconfigure(1, weight=2)

for x in range (len(food)):
    foodop = Label(myFrame3, font=("Impact", "15"), text = food[x])
    foodop.grid(row = 2+x, column = 4) # <--
for x in range (len(foodprice)):
    fprice = Label(myFrame3, font=("Impact", "15"), text = foodprice[x])
    fprice.grid(row = 2+x, column = 8) # <--

for x in range (len(drinks)):
    drinksop = Label(myFrame3, font=("Impact", "15"), text = drinks[x])
    drinksop.grid(row = 4+(len(food))+x, column = 4) # <--
for x in range (len(drinksprice)):
    drinksp = Label(myFrame3, font=("Impact", "15"), text = drinksprice[x])
    drinksp.grid(row = 4+(len(food))+x, column = 8) # <--

标签: pythontkinter

解决方案


在文本周围创建空白区域不像在电子表格程序中那样工作。

如果没有设置权重rowconfigure()来防止这种情况,Tkinter 会折叠完全空的网格行。列也是如此。

像这样的布局:

具有相邻坐标的网格布局

import tkinter as tk

root = tk.Tk()

def place(col, row, text='Label', color='white'):
    label = tk.Label(root, text=text, bg=color)
    label.grid(column=col, row=row, 
        ipadx=10, ipady=10, padx=1, pady=1, sticky="NSEW")

def make_layout(cols, rows):

    for c in cols:
        place(c, 0, c, 'lightgrey')
        
    for r in rows:
        place(0, r, r, 'lightgrey')

    for r in rows:
        for c in cols:
            place(c, r, 'Label')

make_layout((1,2),(1,2))

root.mainloop()

...看起来完全像这样:

具有远坐标的网格布局

无需将列中的权重配置829,行中的权重549

(要得到这个,在代码中替换make_layout((1,2),(1,2))make_layout((7,30),(4,50))!)

即使您添加了权重,标签仍然高于加权的空行,因此布局可能看起来不像您想象的那么干净。

Tkinter 的 Grid Geometry Manager是我前几天阅读的一个很好的教程,其中详细介绍了这一点。还介绍了函数的可选columnspanrowspan参数grid()

最后但并非最不重要的一点是,您应该看看如何在 Tkinter 中的标签中证明文本的合理性


推荐阅读