我是Tkinter的新手,我有一个Listbox
小部件,当您更改主窗口的大小时,我想自动调整其大小。
基本上,我希望有一个高度/宽度可变的列表框。如果有人可以指出一些文档或提供一些代码/见解,我将不胜感激。
import Tkinter as tk
root = tk.Tk()
scrollbar = tk.Scrollbar(root, orient="vertical")
lb = tk.Listbox(root, width=50, height=20, yscrollcommand=scrollbar.set)
scrollbar.config(command=lb.yview)
scrollbar.pack(side="right", fill="y")
lb.pack(side="left",fill="both", expand=True)
for i in range(0,100):
lb.insert("end", "item #%s" % i)
root.mainloop()
规格:
Windows 7,Python 3.8.1,tkinter版本:8.6
我发现最简单的方法是利用
。pack()方法。关键是使用fill=
和expand=True
选项。
import tkinter as tk
root=tk.Tk() #Creates the main window
listbox=tk.Listbox(root) #Create a listbox widget
listbox.pack(padx=10,pady=10,fill=tk.BOTH,expand=True) #fill=tk.BOTH, stretch vertically and horizontally
#fill=tk.Y, stretch vertically
#fill=tk.X, stretch horizontally
框架
如果将列表框放在框架中,则框架还需要使用fill=
和expand=True
选项。
import tkinter as tk
root=tk.Tk()
frame1=tk.Frame(root)
frame1.pack(fill=tk.BOTH, expand=True)
listbox=tk.Listbox(frame1)
listbox.pack(padx=10,pady=10,fill=tk.BOTH,expand=True)
要检查您的tkinter版本,请使用:import tkinter as tk print(tk.TkVersion)
如果您想了解
fill和expand之间的区别,请参见以下链接。https://effbot.org/tkinterbook/pack.htm