Dessin de graphes en TkInter


Introduction au dessin en Tkinter

Tkinter est un module d'interface graphique pour Python. On crée une fénêtre principale en écrivant simplement :

import tkinter 

root= tkinter.Tk() 
root.title ("my demo")
root.mainloop()

On peut ensuite insérer une surface dessinable (canvas) dans la fenêtre principale :

import tkinter 

root= tkinter.Tk() 
root.title ("my demo")
canvas= tkinter.Canvas(root, width=800, height=800, bg="white")
canvas.pack()
root.mainloop()

On peut ensuite insérer des dessins dans le canvas. Le programme ci-dessous insère cinq dessins: un carré bleu, un disque rose, une ligne brisée en pointillé gris, une courbe de Bézier noire fléchée, un texte centré en police Courier.

import tkinter 

def draw_samples (canvas):
    canvas.create_rectangle ((100, 100), (600, 600),  
                             fill="cyan", outline="blue", width=5)

    canvas.create_oval ((100, 100), (600, 600), 
                        fill="pink", outline="red", width=3)

    canvas.create_line ((100, 100), (500, 200),(600, 600), 
                        fill="gray", width=3, dash=(8,4))

    canvas.create_line ((100, 100), (500, 200), (600, 600), 
                        fill="black", width=5, smooth=True,
                        arrow="last", arrowshape=(30,45,15))
 
    canvas.create_text (600, 100, text= "Hello\nEverybody",
                        fill= "black", font= ("courier", 30, "bold italic"),
                        anchor="center", justify= "center")

root= tkinter.Tk()
root.title ("demo")
canvas=tkinter.Canvas(root, width=800, height=800, bg="white")
canvas.pack()
draw_samples (canvas)
root.mainloop()

On obtient le dessin suivant (hormis la grille, que l'on demande d'écrire) :

Exercices de dessin en Tkinter