简体   繁体   English

python tkinter 在运行时将新按钮添加到可滚动框架

[英]python tkinter add new buttons at runtime to scrollable frame

the code below will add 10 buttons in scrollable frame however what i want is to be able to add new buttons at anytime while the app is running so i want it to add new buttons to the scrollable frame when ever i click any keyboard button however the code below doesn't do that and there is no error messages下面的代码将在可滚动框架中添加 10 个按钮但是我想要的是能够在应用程序运行时随时添加新按钮所以我希望它在我单击任何键盘按钮时向可滚动框架添加新按钮但是下面的代码没有这样做,并且没有错误消息

from tkinter import *
from tkinter import ttk

root = Tk()
root.geometry("500x400")

main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)

my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

my_scrollbar = ttk.Scrollbar(main_frame, 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")))

second_frame = Frame(my_canvas)

my_canvas.create_window((0,0), window=second_frame, anchor="nw")

for i in range(10):
    Button(second_frame, text=str(i)).grid(row=i, column=0, pady=10, padx=10)

def onKeyPress(event):
        global second_frame
        print("key clicked")
        Button(second_frame, text='test').grid(row=10, column=0, pady=10, padx=10)
        
root.bind('<KeyPress>', onKeyPress)
root.mainloop()

The button is being added.正在添加按钮。 However, you're not updating the scrollregion of the canvas so you can't see it because the frame becomes larger than the scrollable region.但是,您没有更新scrollregion的滚动区域,因此您看不到它,因为框架变得大于可滚动区域。

One solution is to add one line to onKeyPress :一种解决方案是在onKeyPress中添加一行:

def onKeyPress(event):
    ...
    my_canvas.configure(scrollregion=my_canvas.bbox("all"))

For a more general solution, you can instead add a binding to the <Configure> event of the inner frame, since that event fires whenever the frame grows or shrinks.对于更通用的解决方案,您可以改为将绑定添加到内部框架的<Configure>事件,因为该事件会在框架增长或缩小时触发。

second_frame.bind("<Configure>", lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM