tkinter使用pack和grid實現縮放布局


pack

關鍵是理解side,anchor,expand,fill的使用。

有一篇文章寫的不錯,但是要耐心看,反復看,不容易理解。

https://blog.csdn.net/superfanstoprogram/article/details/83713196

import tkinter as tk
import tkinter.ttk as ttk

win=tk.Tk()
win.title("CommunicationTool")
#setting
setFrame = tk.LabelFrame(win,text="Setting")
comFrame = tk.Frame(setFrame)
comLable = tk.Label(comFrame,text="COM Port: ").pack(side=tk.LEFT)
comSpiner = tk.Spinbox(comFrame,text="COM1").pack(side=tk.LEFT)
refrashButton = ttk.Button(comFrame,text="Refresh").pack(side=tk.LEFT)
comFrame.pack(anchor=tk.W)
cmdFrame = tk.Frame(setFrame)
inputLable = tk.Label(cmdFrame,text="Command: ").pack(side=tk.LEFT)
inputEntry = tk.Entry(cmdFrame).pack(side=tk.LEFT,expand=1,fill=tk.X)
sendButton = ttk.Button(cmdFrame,text="Send").pack(side=tk.LEFT)
cmdFrame.pack(anchor=tk.W,expand=1,fill=tk.X)
setFrame.pack(fill=tk.BOTH)
#output
outputFrame = tk.LabelFrame(win,text="Output")
area = tk.Text(outputFrame).pack(expand=1,fill=tk.BOTH)
outputFrame.pack(expand=1,fill=tk.BOTH)

win.mainloop()
  

  

 grid

默認情況下,grid中的部件不縮放。

縮放的關鍵:

rowconfigure()
columnconfigure()

示例代碼:
import tkinter as tk
import tkinter.ttk as ttk

win=tk.Tk()
win.title("CommunicationTool")
win.rowconfigure(1, weight=1)
win.columnconfigure(0, weight=1)
#setting
setFrame = tk.LabelFrame(win,text="Setting")
setFrame.columnconfigure(2, weight=1)
comLable = tk.Label(setFrame,text="COM Port: ").grid(row=0,column=0)
comSpiner = tk.Spinbox(setFrame,text="COM1").grid(row=0,column=1,sticky=tk.EW)
refrashButton = ttk.Button(setFrame,text="Refresh").grid(row=0,column=2,sticky=tk.W)
inputLable = tk.Label(setFrame,text="Command: ").grid(row=1,column=0)
inputEntry = tk.Entry(setFrame).grid(row=1,column=1,sticky=tk.EW,columnspan=2)
sendButton = ttk.Button(setFrame,text="Send").grid(row=1,column=3)
setFrame.grid(row=0,sticky=tk.EW)
#output
outputFrame = tk.LabelFrame(win,text="Output")
outputFrame.rowconfigure(0,weight=1)
outputFrame.columnconfigure(0,weight=1)
area = tk.Text(outputFrame).grid(row=0,sticky=tk.NSEW)
outputFrame.grid(row=1,sticky=tk.NSEW)

win.mainloop()

默認效果:

最大化效果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM