在Python編程中,使用畫布進行圖形繪制是很常見的。但是當繪制的圖形比較大或者需要進行拖動時,就需要實現畫布的拖動功能。下面介紹一種實現畫布拖動的方法。
from tkinter import * class MoveableCanvas(Canvas): def __init__(self, master=None, **kw): Canvas.__init__(self, master=master, **kw) self.bind("", self.on_button_press) self.bind(" ", self.on_move_press) self.bind(" ", self.on_zoom) self.bind(" ", self.on_zoom) self.bind(" ", self.on_zoom) self.bind(" ", self.on_resize) self.rect = None self.start_x = None self.start_y = None def on_button_press(self, event): self.start_x = self.canvasx(event.x) self.start_y = self.canvasy(event.y) self.rect = self.create_rectangle( self.start_x, self.start_y, self.start_x, self.start_y ) def on_move_press(self, event): cur_x = self.canvasx(event.x) cur_y = self.canvasy(event.y) if self.rect: self.coords(self.rect, self.start_x, self.start_y, cur_x, cur_y) dx = cur_x - self.start_x dy = cur_y - self.start_y self.scan_mark(0, 0) self.scan_dragto(dx, dy, gain=1) def on_zoom(self, event): if event.delta >0: self.scale("all", event.x, event.y, 1.1, 1.1) elif event.delta< 0: self.scale("all", event.x, event.y, 0.9, 0.9) def on_resize(self, event): self.scan_mark(0, 0) self.scan_dragto(event.width, event.height, gain=1) root = Tk() canvas = MoveableCanvas(root, width=800, height=600, bg="white") canvas.pack(fill=BOTH, expand=YES) for i in range(400): for j in range(300): canvas.create_oval(i*5, j*5, i*5+5, j*5+5, fill="blue", outline="blue") root.mainloop()
上述代碼中,定義了一個繼承自Canvas的MoveableCanvas類。在該類中重寫了鼠標按下、拖動、滾輪、調整畫布大小等事件的方法。通過在畫布上創建一個矩形,實現拖動畫布。使用scale方法實現畫布的縮放。
上一篇php js代碼
下一篇ajax不用form提交