Wednesday 9 November 2016

Tkintering with the Turtle

One of the DAH semester modules is CS6102. We here given a very interesting Python starter project assignment as part of CS6102. The brief was to make a fractal generator (using recursion). One of the most time consuming tasks was getting turtle graphics to work with tkinter and draw to a canvas.

Lines 7 to 17 below are a Graphics Pen class, note this uses Rawturtle 

Line 33 is where the canvas is created note its reference to parent
self.canvas = Canvas(self.parent, width=400, height=400)
 
Line 36 is where the Rawturtle is created, this is passed to (line 7):
class GraphicsPen(RawTurtle):
 
Line 47 initializes the RawTurtle with a target of the canvas:
self.graphic = GraphicsPen(self.canvas,0,0,'black',0,3)
 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from turtle import *
from tkinter import *
from tkinter.ttk import *


#Graphics Pen hold the Rawturtle for drawing
class GraphicsPen(RawTurtle):
    def __init__(self,canvas,x,y,color,speed,width):
        RawTurtle.__init__(self,canvas)
        self.ht()
        self.penup()
        self.goto(x,y)
        self.color(color)
        self.speed(speed)
        self.width(width)
        self.pendown()
    #end __init__
    
#Application Class
class Application(Frame):
    
    def __init__(self,parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.makeUI()
        #end __init__

    def makeUI(self):
        self.parent.title('Fractal Generator')

        #Setup the fractal drawing canvas
        self.canvasFrame = LabelFrame(self, text = 'Canvas Space', width=410, height=410)
        self.canvas = Canvas(self.parent, width=400, height=400)
        self.canvas.pack(side=LEFT)

        self.turtle = RawTurtle(self.canvas)
        self.turtle.ht()
        
        screen = self.turtle.getscreen()
        screen.bgcolor('blue')
        
        self.onDraw()

    #end makeUI

    def onDraw(self):
        self.graphic = GraphicsPen(self.canvas,0,0,'black',0,3)
        for i in range(0, 4):
            self.graphic.forward(100)
            self.graphic.left(90)
    #end onDraw

def main():
    root = Tk()
    root.title('Assignment')
    app = Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Running the code above produces the following output


No comments:

Post a Comment