前言
因为毕设的原因,最近在同时学习tkinter和turtle,希望可以在自己需要的GUI上面画出图像。
查看文档
查了一下python中关于turtle的文档,可以发现下面的描述:
TurtleScreen
类定义图形窗口作为绘图海龟的运动场。它的构造器需要一个tkinter.Canvas
或ScrolledCanvas
作为参数。应在turtle
作为某个程序的一部分的时候使用。Screen()
函数返回一个TurtleScreen
子类的单例对象。此函数应在turtle
作为独立绘图工具时使用。
RawTurtle
(别名:RawPen
) 类定义海龟对象在TurtleScreen
上绘图。它的构造器需要一个 Canvas, ScrolledCanvas 或 TurtleScreen 作为参数,以指定 RawTurtle 对象在哪里绘图。Turtle
(别名:Pen
),该类对象在Screen
实例上绘图,如果实例不存在则会自动创建。
程序
import turtle
from tkinter import *
def drawp():
theScreen = turtle.TurtleScreen(canva)
path = turtle.RawTurtle(theScreen)
path.forward(100)
path.right(90)
path.forward(150)
theScreen.mainloop()
root = Tk()
root.title("the path")
canva = Canvas(root, width=400, height=400)
canva.pack()
aa = Button(root, text="Draw", command=drawp)
aa.pack()
root.mainloop()
总结
相对于经常用到的 turtle 独立绘图,关键在于下面两条语句的区别:
#独立绘图
theScreen = turtle.Screen()
path = turtle.Turtle()
#在tkinter画布上绘图
theScreen = turtle.TurtleScreen(canva)
path = turtle.RawTurtle(theScreen)
#path = turtle.RawTurtle(canva) #参数换成canva也可以