Home > Software design >  python tkinter add new buttons at runtime to scrollable frame
python tkinter add new buttons at runtime to scrollable frame

Time:02-06

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

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()

CodePudding user response:

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.

One solution is to add one line to 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.

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