畫布具有內置的用於與鼠標滾動支持經由scan_mark
和scan_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:我不認爲它是無限的,但實際限制沒有記錄。只要試着讓scrollregion越來越大。我的猜測是,座標是32位整數。 –
再次感謝這個滾動代碼@BryanOakley。對於「縮放」,你會使用「canvas.scale」這樣的東西嗎?我在縮放時從零開始做了一個實現,但我認爲'tkinter'中可能內置了一些內容? – Basj