是否可以使按钮在画布内滚动?

时间:2019-07-10 17:48:36

标签: python-3.x tkinter tkinter-canvas

我一直在尝试使画布内的按钮可滚动,但是它不会滚动。

我尝试将其放置在ListBox,画布,框架中无法使用。我已经尝试了所有事情,但现在仍然不知道该怎么做。

from tkinter import *

FrameU = Tk()
frameN=Frame(FrameU,width=540,height=800,bg="#A0522D")
frameN.place(x=0,y=0,relx=.2,rely=.2)
canvas=Canvas(frameN,bg="#A0522D",width=400,height=800)
scrollbar = Scrollbar(frameN, orient = VERTICAL,width=20,relief=SUNKEN)
scrollbar.pack(side=RIGHT, fill=Y)
scrollbar.config(command=canvas.yview)
canvas.config(width=540,height=800,relief=SUNKEN)
canvas.config(yscrollcommand=scrollbar.set)



mylist=Listbox(canvas,bg="#A0522D",width=100,height=41,bd=5,highlightthickness=0,yscrollcommand=scrollbar.set )
for i in range(100):
    mylist.insert(END, i)

b = Button(canvas,bg="blue",width=5,height=5)
b.place(rely=.5,relx=.5)

mylist.config(yscrollcommand=scrollbar.set)
mylist.pack(side=LEFT,fill=BOTH)
canvas.pack(side=LEFT)

我没有收到任何错误或任何其他信息,但是如果将其放置在列表框内,它将显示在“ for range(100)中的我:”中,它显示在画布“。!frame。!canvas。!listbox中”。 !按钮”

1 个答案:

答案 0 :(得分:0)

可滚动按钮。您是说按钮的位置随滚动条滑块的移动而变化吗?乍看之下,这似乎是不可能的。

但是您可以将回调函数绑定到滚动条,并且此函数将与鼠标移动滚动条滑块同步更改按钮位置。这是一个工作示例:

from tkinter import *
from tkinter import ttk

rx, ry = 0.45, 0.45           # the button position (relative)

root=Tk()

wCanvas, hCanvas = 400, 350   # size of canvas
w1, h1 = 800, 700             # size of scrollable area

vBar = ttk.Scrollbar(root, orient = VERTICAL)
can1 = Canvas(root, scrollregion = (0,0,w1,h1), width = wCanvas, height = hCanvas, yscrollcommand = vBar.set)
vBar['command'] = can1.yview

vBar.pack(side=RIGHT,fill=Y)
can1.pack()

can1.create_line(10, 10, 100, 100)   # for canvas scrolling confirmation only

but1 = Button(can1)
but1.place(relx = rx, rely = ry)

def VscrollBarMove(event):  # callback function
    but1.place(relx = rx, rely = ry + vBar.get()[0])  # Scrollbar.get() returns a tuple with relative positions of upper (for vertical scrollbar) and lower edges of a slider

vBar.bind('<B1-Motion>', VscrollBarMove)

root.mainloop()

用于两键情况的回调函数的版本:

def VscrollBarMove(event):  # callback function
    but1.place(relx = rx, rely=ry+vBar.get()[0])
    but2.place(rely = ry2 + vBar.get()[0])  # You can set the only desirable coordinate if You want
相关问题