DEV Community

Cover image for paint with tkinter
petercour
petercour

Posted on

4 1

paint with tkinter

Tkinter is a module to build Graphical User Interfaces (GUI). That is desktop software, likely the one you are using right now.

Most desktop software is all about buttons, text fields and that kind of stuff. What about paint? The fun stuff? How do you create a paint window.

In the code below a canvas widget is created, on which you can paint.

An important method is

#!/usr/bin/python3
def test_drag(self,event):
   self.canvas.create_oval(event.x,event.y,event.x+1,event.y+1)

That creates an oval on the mouse position. The +1 means the size. You can change the size, like

#!/usr/bin/python3
def test_drag(self,event):
   self.canvas.create_oval(event.x,event.y,event.x+10,event.y+10)

Ok so what does the code look like?

#!/usr/bin/python3
from tkinter import *

class application(Frame):
    def __init__(self,master):
        super().__init__(master)
        self.master=master
        self.pack()
        self.createWidget()

    def createWidget(self):

        self.canvas = Canvas(
        self,width=200,height=200,bg='white')
        self.canvas.pack()
        self.canvas.bind('<Button-1>',self.mouseTest)
        self.canvas.bind('<B1-Motion>',self.test_drag)
        self.canvas.bind('<KeyPress>',self.keyboard_test)
        self.canvas.bind('<KeyPress-a>',self.press_a_test)
        self.canvas.bind('KeyRelease-a',self.release_a_test)

    def mouseTest(self,event):
        print('{0},{1}'.format(event.x,event.y))
        print('{0},{1}'.format(event.x_root,event.y_root))
        print('{0}'.format(event.widget))

    def test_drag(self,event):
        self.canvas.create_oval(event.x,event.y,event.x+1,event.y+1)

    def keyboard_test(self,event):
        print('keycode:{0},char:{1},keysym:{2}'.format(event.keycode,event.char,event.keysym))

    def press_a_test(self,event):
        print('press a')

    def release_a_test(self):
        print('release a')

if __name__ == '__main__':
    root = Tk()
    root.geometry('200x200')
    app=application(root)
    root.mainloop() 

Enjoy drawing!

Learn more:

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay