乌龟写意画

时间:2016-08-31 12:39:28

标签: python turtle-graphics tkinter-canvas

我正在开发一个结合了Tkinter和Turtle模块的简单绘图程序。

我想添加一个选项,用户可以通过使用类似于Paint上的笔小部件的鼠标来绘制任何内容。我尝试了很多东西,我无法弄清楚我是怎么做到的。如何让乌龟在画布上用鼠标画任何东西(比如画笔上的笔画框)

from tkinter import *
import turtle

sc=Tk()
sc.geometry("1000x1000+100+100")

fr4=Frame(sc,height=500,width=600,bd=4,bg="light green",takefocus="",relief=SUNKEN)

fr4.grid(row=2,column=2,sticky=(N,E,W,S))

#Canvas
canvas = Canvas(fr4,width=750, height=750)
canvas.pack()

#Turtle
turtle1=turtle.RawTurtle(canvas)
turtle1.color("blue")
turtle1.shape("turtle")

points=[]

spline=0

tag1="theline"

def point(event):
    canvas.create_oval(event.x, event.y, event.x+1, event.y+1, fill="red")
    points.append(event.x)
    points.append(event.y)
    return points

def canxy(event):
    print (event.x, event.y)

def graph(event):
    global theline
    canvas.create_line(points, tags="theline")

def toggle(event):
    global spline
    if spline == 0:
        canvas.itemconfigure(tag1, smooth=1)
        spline = 1
    elif spline == 1:
        canvas.itemconfigure(tag1, smooth=0)
        spline = 0
    return spline

canvas.bind("<Button-1>", point)

canvas.bind("<Button-3>", graph)

canvas.bind("<Button-2>", toggle)

sc.mainloop()

1 个答案:

答案 0 :(得分:2)

以下代码将让您用乌龟徒手画画。您需要与代码的其余部分集成:

import tkinter
import turtle

sc = tkinter.Tk()
sc.geometry("1000x1000+100+100")

fr4 = tkinter.Frame(sc, height=500, width=600, bd=4, bg="light green", takefocus="", relief=tkinter.SUNKEN)

fr4.grid(row=2, column=2, sticky=(tkinter.N, tkinter.E, tkinter.W, tkinter.S))

# Canvas
canvas = tkinter.Canvas(fr4, width=750, height=750)
canvas.pack()

# Turtle
turtle1 = turtle.RawTurtle(canvas)
turtle1.color("blue")
turtle1.shape("turtle")

def drag_handler(x, y):
    turtle1.ondrag(None)  # disable event inside event handler
    turtle1.goto(x, y)
    turtle1.ondrag(drag_handler)  # reenable event on event handler exit

turtle1.ondrag(drag_handler)

sc.mainloop()