如何設定 Tkinter 網格的特定行和列數?


在 Tkinter 中,你可以使用不同的幾何管理器來設定應用程式的 GUI。網格幾何管理器是 tkinter 中最有用的幾何管理器之一,用於使用二維幾何形式設定應用程式中各個元件的位置。

藉助網格幾何管理器,你可以設定特定數量的行和列,並將元件置於應用程式的任意位置。要設定特定數量的行和列,你需要指定行配置和列配置的 size 值,這有助於設定特定元件的位置。

示例

在以下示例中,我們建立了一個標籤元件,並使用網格幾何管理器設定了 window 的行和列位置。

# Import the required library
from tkinter import*

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Add a label widget
label1 = Label(win, text='Label1', font=("Calibri, 15"))
label1.grid(column=1, row=2)

label2 = Label(win, text='Label2', font=("Calibri, 15"))
label2.grid(column=3, row=5)

label3 = Label(win, text='Label3', font=("Calibri, 15"))
label3.grid(column=5, row=8)

label4 = Label(win, text='Label4', font=("Calibri, 15"))
label4.grid(column=7, row=11)

# set size of the window and add row and column
win.rowconfigure(9)
win.columnconfigure(9)

win.mainloop()

輸出

執行以上程式碼將顯示一個 window,其中標籤元件沿著視窗的行和列設定。

更新日期:2021 年 12 月 16 日

3 千 + 瀏覽

職業生涯快速起步

透過完成課程獲得認證

開始
廣告
© . All rights reserved.