在 tkinter 中更新滚动条

Update scrollbar in tkinter

我正在 python 中编写一些程序,我需要创建一个滚动条,当新的小部件添加到 window 时它会更新。我不知道该怎么做,也没有在任何地方找到答案。有这个命令吗?这是我现在的代码。

import tkinter as tk

root = tk.Tk()
root.geometry("600x400")

my_canvas = tk.Canvas(root)
my_canvas.pack(side = "left", fill = "both", expand = 1)

my_scrollbar = tk.Scrollbar(root, orient = "vertical", command = my_canvas.yview)
my_scrollbar.pack(side = "right", fill = "y")
my_canvas.configure(yscrollcommand = my_scrollbar.set)
my_canvas.bind("<Configure>", lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

my_frame = tk.LabelFrame(my_canvas, width = my_canvas.winfo_width())
my_frame.grid_propagate(0)
my_frame.pack()

for i in range(10):
    my_label = tk.Label(my_frame, text = "Label")
    my_label.pack()

my_canvas.create_window((0, 0), width = 600, anchor = "nw", window = my_frame)

def create_label(scroll, canv, fram):
    my_label = tk.Label(fram, text="Label")
    my_label.pack()
   


my_button = tk.Button(my_frame, text = "Button", command = lambda: create_label(my_scrollbar, my_canvas, my_frame))
my_button.pack()

root.mainloop()

绑定到内框的<Configure>事件。每当框架改变大小时,该事件就会触发。

def adjust_scrollregion(event):
    my_canvas.configure(scrollregion=my_canvas.bbox("all"))
my_frame.bind("<Configure>", adjust_scrollregion)

与所问问题无关...调用 my_frame.grid_propagate(0) 毫无意义,因为您在 my_frame.

中使用了 pack