Hung Truong
Hung Truong

Reputation: 369

Tkinter : Make canvas draggable

i am creating a project that involves making a RawTurtle on a canvas. And I was wondering what would I do if the drawing is out of the screen. Can anyone tell me how to make the Tkinter Canvas widget draggable ?

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

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

Upvotes: 1

Views: 2026

Answers (1)

James Kent
James Kent

Reputation: 5933

this is an answer for python 3, but change the imports and it should work fine with 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()

worth noting:

  1. for some reason once a turtle is added the canvas bindings stop working, the best fix for this is to add the bindings after adding the turtles. alternatively you can bind to the top window instead.
  2. the canvas can only be panned to the edge of its scroll region, if you want to pan further you'll need to make this bigger.

Upvotes: 3

Related Questions