簡體   English   中英

在tkinter中更改滾動條的大小(使用網格布局)

[英]Changing the size of a scrollbar in tkinter(using grid layout)

我正在制作一個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個可見。

每當框架更改大小並重新繪制項目時,都需要重置滾動區域。

這樣做的通常方法是綁定到框架的<Configure>事件,以便它隨着框架的增長和收縮而自動發生。

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM