使用 Tkinter 网格方法,我想将标签居中

With Tkinter grid method, i want to center the labels

当我使用网格方法时,文本没有很好地居中。

在下面的示例中,我想让标签“第 0 列第 0 行”和“第 0 列第 1 列”居中。

这是一个例子:

import tkinter as tk


class GUI(tk.Tk):
   
    def __init__(self):
        
        tk.Tk.__init__(self)
        
        self.frame1 = tk.LabelFrame(self, text="frame #1")
        self.frame1.grid(row=0, column=0)
        
        self.l1f1 = tk.Label(self.frame1, text="vvvvvvvvvveeeeeeeerrrryyyyyy "
                             "llllllllooooonnnngggg tttttteeeeeexxxxxxtttttt")
        self.l1f1.grid(row=0, column=0)
        
        self.frame2 = tk.LabelFrame(self, text="frame #2")
        self.frame2.grid(row=1, column=0, sticky="ew")
        
        self.l1f2 = tk.Label(self.frame2, text="  row 0 col 0  ")
        self.l1f2.grid(row=0, column=0)
        
        self.l2f2 = tk.Label(self.frame2, text="  row 0 col 1  ")
        self.l2f2.grid(row=0, column=1)

        self.update()
        
        
mygui = GUI()
mygui.mainloop()

我用这个方法找到了解决方案

grid_columnconfigure(index, weight)

将权重设置为“1”,列将使用整个可用宽度。

import tkinter as tk

class GUI(tk.Tk):
   
    def __init__(self):
        
        tk.Tk.__init__(self)
        
        self.frame1 = tk.LabelFrame(self, text="frame #1")
        self.frame1.grid(row=0, column=0)
        
        self.l1f1 = tk.Label(self.frame1, text="vvvvvvvvvveeeeeeeerrrryyyyyy "
                             "llllllllooooonnnngggg tttttteeeeeexxxxxxtttttt")
        self.l1f1.grid(row=0, column=0)
        
        self.frame2 = tk.LabelFrame(self, text="frame #2")
        self.frame2.grid(row=1, column=0, sticky="ew")
        
        self.frame2.grid_columnconfigure(0, weight=1)
        self.frame2.grid_columnconfigure(1, weight=1)
        
        self.l1f2 = tk.Label(self.frame2, text="  row 0 col 0  ")
        self.l1f2.grid(row=0, column=0)
        
        self.l2f2 = tk.Label(self.frame2, text="  row 0 col 1  ")
        self.l2f2.grid(row=0, column=1)

        self.update()        
        
mygui = GUI()
mygui.mainloop()