简体   繁体   English

为什么滚动条在 canvas (tkinter) 中不起作用?

[英]Why is the scrollbar not working in the canvas (tkinter)?

I want the window frame to expand the whole canvas AND have a scrollbar.我想要 window 框架来扩展整个 canvas 并有一个滚动条。 Now the scrollbar is there visually but is not working as a scrollbar.现在滚动条在视觉上就在那里,但不能用作滚动条。

root = Tk()

def onCanvasConfigure(e):
    my_canvas.configure(scrollregion = my_canvas.bbox("all")) #make the scrollfunction work
    my_canvas.itemconfig('window', height=(my_canvas.winfo_height()-100), width=(my_canvas.winfo_width()-100)) #set the frame window to canvas size


#Below code to add scrollbar to app. 
# Layers (root -> main_frame -> my_canvas -> window (frame))

# Create A Main Frame
main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)

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

# Add A Scrollbar To The Canvas
my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)

# Configure The Canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)


# Create ANOTHER Frame INSIDE the Canvas
window = Frame(my_canvas)

# Add that New frame To a Window In The Canvas
my_canvas.create_window((0,0), window=window, anchor="nw", tags="window")

my_canvas.bind("<Configure>", onCanvasConfigure)

See clip: https://jumpshare.com/v/TJlbWJac5d4rwp3DwnFw见剪辑: https://jumpshare.com/v/TJlbWJac5d4rwp3DwnFw

Since you resize the internal frame window to the same size of canvas, so the scrollregion will be around the same as the size of the canvas which makes the scrollbar not activated.由于您将内部框架window的大小调整为与 canvas 相同的大小,因此滚动区域将与scrollregion的大小大致相同,这使得滚动条未激活。

If you set the height of the frame larger than that of canvas, the scrollbar will be activated:如果您设置的框架高度大于 canvas 的高度,将激活滚动条:

def onCanvasConfigure(e):
    # resize the frame with double height of canvas
    my_canvas.itemconfig('window', height=e.height*2, width=e.width)
    # update scrollregion
    my_canvas.configure(scrollregion=my_canvas.bbox("all"))

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

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