在tkinter中更改滚动条的大小(使用网格布局)

时间:2019-05-31 16:01:29

标签: python tkinter python-3.7

我正在制作一个Tkinter GUI,它允许您查询数据库并将结果显示在可滚动的框架中。但是,当您生成结果时,滚动条将不会调整以匹配框架的新大小。如何获取滚动条以显示所有结果?我整理了一个快速而肮脏的代码版本,以演示我遇到的问题。

import tkinter as tk

def Lookup():
    list = frame_buttons.grid_slaves()
    for l in list:
        l.destroy()
    for x in range(1000):
        tk.Label(frame_buttons, text="test", background="white").grid(row=x)


root = tk.Tk()
root.grid_rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)

frame_main = tk.Frame(root, bg="white")
frame_main.grid(row = 0,sticky='news')
frame_input = tk.Frame(frame_main, background = "white")
frame_input.grid(row=0, column=0, pady=(5, 0), sticky='nw')

tk.Button(frame_input, text="Search", fg="black", background = "grey",command=Lookup).grid(row=3, column=0,sticky='nw')

# Create a frame for the canvas with non-zero row&column weights
frame_canvas = tk.Frame(frame_main)
frame_canvas.grid(row=1, column=0, pady=(5, 0), sticky='nw')
frame_canvas.grid_rowconfigure(0, weight=1)
frame_canvas.grid_columnconfigure(0, weight=1)
# Set grid_propagate to False to allow 5-by-5 buttons resizing later
frame_canvas.grid_propagate(False)

# Add a canvas in that frame
canvas = tk.Canvas(frame_canvas, bg="gray")
canvas.grid(row=0, column=0, sticky="news")

# Link a scrollbar to the canvas
vsb = tk.Scrollbar(frame_canvas, orient="vertical", command=canvas.yview)
vsb.grid(row=0, column=1, sticky='ns')
canvas.configure(yscrollcommand=vsb.set)
frame_buttons = tk.Frame(canvas, bg="gray")
canvas.create_window((0, 0), window=frame_buttons, anchor='nw')
for x in range(15):
    tk.Label(frame_buttons, text="blah", background = "white").grid(row=x)
frame_buttons.update_idletasks()
frame_canvas.config(width=500, height=100)
canvas.config(scrollregion=canvas.bbox("all"))
root.mainloop()

这最初会在滚动区域中放置20个标签,足以激活滚动条。然后,当您单击搜索时,它将用1000个测试标签替换这20个标签。但是只有前20个可见。

1 个答案:

答案 0 :(得分:0)

每当框架更改大小并重新绘制项目时,您都需要重置滚动区域。

执行此操作的正常方法是绑定到框架的<Configure>事件,以使其随着框架的增长和收缩而自动发生。

示例:

def reset_scrollregion(event):
    canvas.config(scrollregion=canvas.bbox("all"))
...
frame_buttons.bind("<Configure>", reset_scrollregion)