简体   繁体   English

Tkinter 滚动条不适用于画布内的对象

[英]Tkinter Scrollbar Does not work for objects inside canvas

I've made a canvas with two scrollbar and two buttons.我制作了一个带有两个滚动条和两个按钮的画布。 But the scrollbar doesn't interact with the buttons inside the canvas.但是滚动条不与画布内的按钮交互。 What I want to make, is whenever I scrolls (for example, scroll down), all buttons in the canvas moves to the opposite direction (in this case, move up), but currently they won't move at all.我想要做的是,每当我滚动(例如,向下滚动)时,画布中的所有按钮都会向相反的方向移动(在这种情况下,向上移动),但目前它们根本不会移动。

ws = Tk()
ws.title('PythonGuides')

frame = Frame(
    ws,
    width=500,
    height=400
)
frame.pack(expand=True, fill=BOTH)

canvas = Canvas(
    frame,
    bg='#4A7A8C',
    width=500,
    height=400,
    scrollregion=(0, 0, 700, 700)
)

vertibar = Scrollbar(
    frame,
    orient=VERTICAL
)
vertibar.pack(side=RIGHT, fill=Y)
vertibar.config(command=canvas.yview)

horibar = Scrollbar(
    frame,
    orient=HORIZONTAL
)
horibar.pack(side=BOTTOM, fill=X)
horibar.config(command=canvas.xview)

canvas.config(width=500, height=400)

canvas.config(
    xscrollcommand=horibar.set,
    yscrollcommand=vertibar.set
)

example=tkinter.Button(canvas, text="1")
example.grid(row=3, column=5)

example2 = tkinter.Button(canvas, text="2")
example2.grid(row=6, column=7)

canvas.pack(expand=True, side=LEFT, fill=BOTH)

ws.mainloop()

You cannot scroll items of canvas if they are put into the canvas using .grid()/.pack()/.place() .如果使用.grid()/.pack()/.place()将画布项目放入画布,则无法滚动画布项目。

Use .create_window() instead:使用.create_window()代替:

...
example = tkinter.Button(canvas, text="1")
canvas.create_window(10, 10, window=example, anchor="nw")

example2 = tkinter.Button(canvas, text="2")
canvas.create_window(50, 50, window=example2, anchor="nw")
...

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

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