如何使Tkinter列表框适合内容 [英] How to fit Tkinter listbox to contents
问题描述
我正在使用以下代码将字符串添加到列表框中.当我运行代码并打开窗口时,较长的字符串会被裁剪,因为窗口不够大(请参见屏幕截图).我尝试过使窗口可调整大小并添加滚动条,但是我想知道是否有一种自动调整窗口大小以适合内容的方法.
I'm adding strings to a listbox using the code below. When I run the code and the window opens, the longer strings get clipped as the window is not large enough (see screenshot). I have tried making the window resizeable and adding scroll bars but I was wondering if there was a way to automatically size it to fit the content.
master = tk.Tk()
listbox = tk.Listbox(master, selectmode=tk.SINGLE)
games = ["Garry's Mod", "Mount and Blade: Warband", "Tekkit"]
for game in sorted(games):
listbox.insert(tk.END, game)
button = tk.Button(master, text="Execute", command=execute)
listbox.pack()
button.pack()
tk.mainloop()
推荐答案
重置列表框宽度对我有用.我使用了遗忘的答案,发现宽度始终为零.
Resetting the listbox width worked for me. I used the Oblivion's answer and noticed that the width is always zero.
listbox = tk.Listbox(master, selectmode=tk.SINGLE)
listbox.config(width=0)
我还建议在重新加载列表内容后重置根窗口的几何形状.否则,如果用户手动扩展窗口,则该窗口将停止容纳其内容的大小.
I also recommend to reset the root window geometry after reloading a content of the list. Otherwise if user manually extends a window the window would stop accommodate size of its content.
root.winfo_toplevel().wm_geometry("")
这篇关于如何使Tkinter列表框适合内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!