Tkinter:使画布可拖动

时间:2016-07-15 08:34:22

标签: python canvas tkinter drag

我正在创建一个涉及在画布上制作RawTurtle的项目。而且我想知道如果绘图不在屏幕上我会怎么做。谁能告诉我如何使Tkinter Canvas小部件可拖动?

from tkinter import *
root = Tk()
c = Canvas(root)
t = RawTurtle(c)

....# What can i do to have a drag function
root.mainloop()

1 个答案:

答案 0 :(得分:3)

这是python 3的答案,但更改导入,它应该可以正常使用python 2

#!python3

import tkinter as tk
import turtle

def run_turtles(*args):
    for t, d in args:
        t.circle(200, d)
    root.after_idle(run_turtles, *args)

def scroll_start(event):
    screen.scan_mark(event.x, event.y)

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

root = tk.Tk()
root.geometry("700x700")
root.withdraw()

frame = tk.Frame(bg='black')
frame.pack(fill='both', expand=True)
tk.Label(frame, text=u'Hello', bg='grey', fg='white').pack(fill='x')

screen = turtle.ScrolledCanvas(frame)
screen.pack(fill="both", expand=True)


turtle1 = turtle.RawTurtle(screen)
turtle2 = turtle.RawTurtle(screen)

screen.bind("<ButtonPress-1>", scroll_start)
screen.bind("<B1-Motion>", scroll_move)

turtle1.ht(); turtle1.pu()
turtle1.left(90); turtle1.fd(200); turtle1.lt(90)
turtle1.st(); turtle1.pd()

turtle2.ht(); turtle2.pu()
turtle2.fd(200); turtle2.lt(90)
turtle2.st(); turtle2.pd()

root.deiconify()

run_turtles((turtle1, 3), (turtle2, 4))

root.mainloop()
值得注意的是:

  1. 由于某种原因,一旦添加了乌龟,画布绑定就会停止工作,最好的解决方法是在添加乌龟后添加绑定。或者你也可以绑定到顶部窗口。
  2. 画布只能平移到其滚动区域的边缘,如果你想进一步平移,你需要将它做得更大。