如何建立具有固定大小的 Tkinter 視窗

Jinku Hu 2022年3月21日
如何建立具有固定大小的 Tkinter 視窗

預設情況下,即使你在初始化視窗例項時指定了寬度和高度,Tkinter 視窗的大小也可調整。

import tkinter as tk

app = tk.Tk()

app.geometry("200x200")

app.mainloop()

你可以拖動上述程式碼建立的視窗以獲取不同的視窗大小。應該使用 resizable 函式來限制寬度和高度是否可變。

import tkinter as tk

app = tk.Tk()

app.geometry("200x200")
app.resizable(width=0, height=0)

app.mainloop()

app.resizable(width=0, height=0) 設定寬度和高度都不能調整。

將框架設定為固定大小

視窗內部的框架與視窗有點類似,即使定義了框架的寬度和高度,它也會自動調整自身大小。

import tkinter as tk

app = tk.Tk()

app.geometry("200x200")
app.resizable(0, 0)

backFrame = tk.Frame(master=app, width=200, height=200, bg="blue").pack()

button1 = tk.Button(master=backFrame, text="Button 1", bg="blue", fg="red").pack()
button2 = tk.Button(master=backFrame, text="Button 2", bg="blue", fg="green").pack()
button3 = tk.Label(master=backFrame, text="Button 3", bg="red", fg="blue").pack()

app.mainloop()

我們期望的 GUI 如下所示,

Tkinter 框架無法調整大小

但是執行上面的程式碼後我們得到的是

Tkinter 框架可調整大小

框架 backFrame 會自動調整大小以與其附著的控制元件來匹配。換句話說,內部的控制元件 backFrame 控制其父框架的大小。

你可以通過設定 pack_propagate(0) 來禁用框架自動調整來適應其控制元件的大小。

凍結視窗框架大小的正確程式碼是,

import tkinter as tk

app = tk.Tk()

app.geometry("200x200")
app.resizable(0, 0)

backFrame = tk.Frame(master=app, width=200, height=200, bg="blue")
backFrame.pack()
backFrame.propagate(0)

button1 = tk.Button(master=backFrame, text="Button 1", bg="blue", fg="red").pack()
button2 = tk.Button(master=backFrame, text="Button 2", bg="blue", fg="green").pack()
button3 = tk.Label(master=backFrame, text="Button 3", bg="red", fg="blue").pack()

app.mainloop()
作者: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - Tkinter Geometry