所以我試圖在 pygame中創建一個 GUI,但過了一會兒,我決定在 tkinter 中重新撰寫它。我需要創建 3 個條,一個是畫布,另一個是空的。左邊欄的大小是leftbarwidth和 右邊rightbarwidth,分別設定為 200 和 300。到目前為止我有這個(不包括程式的邏輯)
1 from tkinter import *
2
3 def windowsizeupdate(event):
4 preview.config(width=event.width-leftbarwidth-rightbarwidth, height=event.height)
5
6 root = Tk()
7 root.title("TITLE HERE")
8 root.geometry(f"{leftbarwidth rightbarwidth 200}x600 {int(screen.winfo_screenwidth() / 2 - (leftbarwidth rightbarwidth 200) / 2)} {int(screen.winfo_screenheight() / 2 - 300)}")
9 root.minsize(800, 600)
10 root.attributes("-topmost", 1)
11
12 preview = Canvas(root, bd=0, bg="#800000", cursor="dot", width=200, height=600)
13 preview.place(x=leftbarwidth, y=0)
14
15 root.bind("<Configure>",windowsizeupdate)
16 root.mainloop()
但是每當我運行它時,我都會得到這個:

在注釋掉第 4 行并將其替換為 之后print(event.width-leftbarwidth-rightbarwidth, event.height, leftbarwidth),我發現一切正常,并且所有值都應該與 config 函式一起使用!
但如果我輸入這個:
1 from tkinter import *
2
3 def windowsizeupdate(event):
4 print(event.width-leftbarwidth-rightbarwidth, event.height, leftbarwidth)
5 preview.config(width=event.width-leftbarwidth-rightbarwidth, height=event.height)
6
7 root = Tk()
8 root.title("TITLE HERE")
9 root.geometry(f"{leftbarwidth rightbarwidth 200}x600 {int(screen.winfo_screenwidth() / 2 - (leftbarwidth rightbarwidth 200) / 2)} {int(screen.winfo_screenheight() / 2 - 300)}")
10 root.minsize(800, 600)
11 root.attributes("-topmost", 1)
12
13 preview = Canvas(root, bd=0, bg="#800000", cursor="dot", width=200, height=600)
14 preview.place(x=leftbarwidth, y=0)
15
16 root.bind("<Configure>",windowsizeupdate)
17 root.mainloop()
我看到我的控制臺輸出如下所示:
誰可以給我解釋一下這個!
uj5u.com熱心網友回復:
因為當您調整視窗大小時,會引發另一個<Configure>事件并呼叫您的處理程式。您需要檢測到您的更改未觸發事件:
def windowsizeupdate(event):
if event.x != leftbarwidth:
preview.config(width=event.width-leftbarwidth-rightbarwidth,
height=event.height)
uj5u.com熱心網友回復:
如果您的目標是將左側和右側視窗保持為固定大小,則無需通過<Configure>事件系結來實作。這類事情正是幾何管理器pack,place和grid的用途。
您正在使用place這使得這個問題更難解決,因為很難讓一個小部件的寬度來填充其他小部件之間的空間。更好的解決方案是使用gridor pack。
例如,使用grid您可以為左右列設定最小大小,然后讓中間列填充所有額外的空間。
from tkinter import *
leftbarwidth = 200
rightbarwidth = 300
root = Tk()
root.minsize(800, 600)
preview = Canvas(root, bd=0, bg="#800000", cursor="dot", width=200, height=600)
root.grid_columnconfigure(0, minsize=leftbarwidth)
root.grid_columnconfigure(2, minsize=rightbarwidth)
root.grid_columnconfigure(1, weight=1)
root.grid_rowconfigure(0, weight=1)
preview.grid(row=0, column=1, sticky="nsew")
root.mainloop()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419072.html
標籤:
