我做了一个滚动条,但我想要我的按钮响应。第二帧未根据 window 进行调整

I have made a scrollbar, but I want my button response. The second frame is not adjusting as per the window

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() 创建的项目,而不是框架
  • 更新 scrollregionsecond 框架调整大小时,而不是 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