用鼠标移动tkinter画布

9
我想通过鼠标点击(按住)+鼠标移动来移动整个tkinter Canvas。我尝试使用canvas.move,但不幸的是它不起作用。
如何在整个画布中滚动? (不是移动画布的每个元素,而是滚动画布的显示区域)
import Tkinter as Tk

oldx = 0
oldy = 0

def oldxyset(event):
    global oldx, oldy
    oldx = event.x
    oldy = event.y

def callback(event):
    # How to move the whole canvas here?
    print oldx - event.x, oldy - event.y

root = Tk.Tk()

c = Tk.Canvas(root, width=400, height=400, bg='white')
o = c.create_oval(150, 10, 100, 60, fill='red')
c.pack()

c.bind("<ButtonPress-1>", oldxyset)
c.bind("<B1-Motion>", callback)

root.mainloop()
1个回答

15

Canvas提供了鼠标滚动的内置支持,通过使用scan_markscan_dragto方法。前者记录了您点击鼠标的位置,后者滚动相应数量的像素。

注意: gain属性告诉scan_moveto每移动一个鼠标像素需要移动多少像素。默认值是10,因此如果您想要鼠标光标与画布之间的1:1对应关系,则需要将此值设置为1(如示例所示)。

以下是一个例子:

import Tkinter as tk
import random

class Example(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.canvas = tk.Canvas(self, width=400, height=400, background="bisque")
        self.xsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.ysb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set)
        self.canvas.configure(scrollregion=(0,0,1000,1000))

        self.xsb.grid(row=1, column=0, sticky="ew")
        self.ysb.grid(row=0, column=1, sticky="ns")
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        for n in range(50):
            x0 = random.randint(0, 900)
            y0 = random.randint(50, 900)
            x1 = x0 + random.randint(50, 100)
            y1 = y0 + random.randint(50,100)
            color = ("red", "orange", "yellow", "green", "blue")[random.randint(0,4)]
            self.canvas.create_rectangle(x0,y0,x1,y1, outline="black", fill=color)
        self.canvas.create_text(50,10, anchor="nw", 
                                text="Click and drag to move the canvas")

        # This is what enables scrolling with the mouse:
        self.canvas.bind("<ButtonPress-1>", self.scroll_start)
        self.canvas.bind("<B1-Motion>", self.scroll_move)

    def scroll_start(self, event):
        self.canvas.scan_mark(event.x, event.y)

    def scroll_move(self, event):
        self.canvas.scan_dragto(event.x, event.y, gain=1)


if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

非常感谢,这正是我所需要的! 是否可以拥有一个无限(或几乎无限)的画布,以便我可以向右/左/上/下滚动到任何位置? - Basj
@Basj:我不认为它是无限的,尽管实际限制没有记录。通过扩大滚动区域进行实验即可。我猜测坐标是32位整数。 - Bryan Oakley
再次感谢@BryanOakley提供的滚动代码。对于“缩放”,您会使用类似canvas.scale的东西吗?当我进行缩放时,我自己从头开始实现了一个实现,但我认为在tkinter中可能有一些内置的东西。 - Basj
我错了吗,还是这个滚动函数不能移动嵌入在Canvas中的Text小部件@BryanOakley?我做了一些测试,似乎它不能移动这样的小部件... - Basj
2
@Basj:这取决于您如何嵌入。如果您使用create_window,它们会随着其他内容一起滚动。如果您使用pack、place或grid,则不会滚动。 - Bryan Oakley
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接