我已经制作了一个滚动条,但我想要我的按钮响应.第二个框架没有根据窗口进行调整


from tkinter import *
root = Tk()
#createe a main frame
main=Frame(root,bg='black')
main.pack(fill=BOTH,expand=1)
#create a Canvas
mycanvas=Canvas(main,bg='red')
mycanvas.pack(side=LEFT,fill=BOTH,expand=1)
# add ascroll bar in canvas
sroll=Scrollbar(main,orient=VERTICAL,command=mycanvas.yview)
sroll.pack(side=RIGHT,fill=Y)
#configure the canvas
mycanvas.configure(yscrollcommand=sroll.set)
#create another frame in canvas
second=Frame(mycanvas,bg='green')
#add that new frame to the window in the canvas
mycanvas.create_window((0,0),window=second,anchor='sw')
def method(event):
mycanvas.configure(scrollregion=mycanvas.bbox("all"))
mycanvas.itemconfigure(second,width=event.width,height=event.height)
mycanvas.bind("<Configure>",method)
root.geometry("500x400")

for thing in range(100):
b=Button(second,text="hellow",width=30).pack(side=TOP,fill=X,padx=30)
root.mainloop()

代码中的几个问题:

  • .create_window(...)中使用anchor="nw"
  • .itemconfigure()应适用于.create_window()创建的项目,而不是框架
  • 调整第二个帧的大小时更新scrollregion,而不是调整mycanvas的大小

以下是代码中所需的更改:

# used anchor="nw" and added tag="second"
mycanvas.create_window((0,0),window=second,anchor='nw',tag="second")
# callback for updating scrollregion
def update_scrollregion(event):
mycanvas.configure(scrollregion=mycanvas.bbox("all"))
# callback for resizing width of "second" frame when "mycanvas" is resized
def resize_frame(event):
# should apply on the item created by create_window(), not "second" frame
mycanvas.itemconfigure("second", width=event.width)
mycanvas.bind("<Configure>", resize_frame) # resize "second" frame whenever "mycanvas" is resized
second.bind("<Configure>", update_scrollregion) # update scrollregion when "second" frame is updated/resized

最新更新