tkinter

Tkinter is a graphical interface that is built into most Python builds.
 
Create a window canvas on which to position other items

import time                                                 #imports time module
from tkinter import *                                   #imports drawing tools
tk=Tk()
can1=Canvas(tk, width=400, height=400)   #Change numbers to change size of window
can1.pack()                                                   #Places the canvas

#Insert all code here

tk.mainloop()                                               #Don't put code underneath this

Understanding how to position items on the canvas
This grid which will help you to plan where to put the shapes
Add a line to the canvas

#Create a line first pair is start of the line x & y
#Second pair is end of the line x & y
line1=can1.create_line(200,200,230,230)
#Make sure the line goes where we said insert code above

 
Add a polygon shape to the canvas
#Create a Polygon
#You can have as many pairs of points as you want
poly1=can1.create_polygon(0,0,10,10,10,100,120,120,140,100)
 
Add a rectangle to the canvas
#Create a rectangle
#First pair is top left point Second pair is bottom right point
rect1=can1.create_rectangle(150,150,200,200)
 
Add text to the canvas
#Create Text
text1=can1.create_text(300,200, text="fred", font="aerial")
 
Add an oval to the canvas
#Create a rectangle and an oval forms inside it
#First pair is top left point Second pair is bottom right point
oval1=can1.create_oval(150,150,200,200)
 
Add simple buttons to the canvas
#Create a function to draw a shape (line in this case)
def line1():
    line1=can1.create_line(200,200,230,230)

#Use the function in a button
but1 = Button(tk, text="OK", command=line1)
but1.pack()
 
Animate simple shapes on the canvas (line, polygon & rectangle)
blob2=can1.create_oval(150,150,200,200) #Create the shape
for x in range(0, 60):            #Repeat everything underneath 60 times
    can1.move(blob2,0,-2)        #Move blob2 X no change Y-2 each loop
    tk.update()                        #Update the window with the new shape position
    time.sleep(0.05)                #Slow it down a little
 
Grow or Shrink shapes

a=150 #create simple variables to put coordinates in
b=150
c=200
d=200

blob2=can1.create_rectangle(a,b,c,d, fill="red") #use variables in place of coordinates
for i in range(60):
    a=a-1 #takes one away from coordinate variable a at top
    b=b-1 #takes one away from coordinate variable b at top
    can1.coords(blob2, a,b,c,d) #redraws the shape using the numbers inside the variables
    tk.update() #updates the canvas
    time.sleep(0.05)
#short time delay

Comments