Tkinter 8: Buttons

Add a button to a window

In this article we will explain how to create a window with a button that makes something when it is pressed.

tkinter button
tkinter button

Buttons

This widget can be added using the tkinter class Button, with a code like the following:

# Create your first button

import tkinter

root = tkinter.Tk()

button1 = tkinter.Button(root, text = "Click me")

button1.pack()

root.mainloop()

Now, you see the button, but when you click it nothing happens. We must add something to this code as we will explain in the next paragraph.

Adding an eventlistener to the button

To add an eventlistener (code that react to an user’s action, like the click con the button), you have to add this code here to the object

button1 = tkinter.Button(root, text = "Click me", command=clicked)

We’ve just added the name of the function that will be called when the user clicks the button. We have to define the function itself with the code that will tell to the program what to do after the click.

Define the function that handle the event

Then you have to tell the computer what to do with a function:

def clicked():

    print("I've been clicked")

This function just prints something on the console each time the button is pressed.

In the next video I will show in detail how to write some code to add a button.

All the code together

# tkinter is the module to create a GUI
import tkinter

# we create the window here and the root to which we will attach the button
# this is an istance of the class Tk(), the main class of tkinter
root = tkinter.Tk()

# before we create the button, we make a function that
# contains the action that takes place when the button's clicked
# the name of the function can be anything, I chose clicked.
def clicked():
	print("Hello world")
	# let's make something to the button
	# you can change the attributes of the button this way
	# putting the name of the attribute in square brackets and apostrophes
	button['text'] = "I have been clicked, dude"

# here we create the BUTTON ====================================
# We give a name to the istance of Button, the class to create it
button = tkinter.Button(root, text="Click me")
# remember then to pack it, otherwise it is not visible
button.pack()

# now we give the name of the function that will handle the click
button['command'] = clicked
# notice that we could have placed 'command' above in the Button class istance
# this is an alternative method


# at the end of the code put the method to create the loop for the window
# it is necessary
root.mainloop()

 

Video

Here is how to create a button in a window.

Tkinter test for students

Tkinter articles

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.