In this Tkinter tutorial let us create a button with Tkinter and then create a function that will change the text of the button once it has been called after the user clicks on that button.
First of all, let us understand the concept of the Tkinter widget staying within the top-level window first. You can think of all the Tkinter widgets are actually wrapped around by that single top-level window object at this moment. Thus every time you create a widget within an object you will need to include the parent object as well, in this case, the top-level window object which is ‘win’ in this case.
hello = ttk.Button(win, text="Hello!", command=lambda: showHello("Hello Again"))
Next, you can specify the position of the button on the window object by using the grid method where in this case the button will be placed on column number 0 and row number 0. The grid method used the cell concept to place the widget within the main window.
hello.grid(column=0, row=0)
In order to call the method and passed some parameters into it, you will use the lambda command within the Button’s constructor as shown below.
command=lambda: showHello("Hello Again")
The original text of the button is ‘Hello’ which is in the text parameter inside the Button constructor.
text="Hello!"
Next, you will need to create a function that will be called by the button once a user has clicked on that particular button. The function will need to be created before the button or else the program will not be able to recognize the function within that button.
def showHello(txt): hello.configure(text=txt) # change the text inside the button
Once the user has clicked on that button the “Hello Again” string will get passed into the above function which will then replace the original text of the button with this latest one!
At last, don’t forget to import the ttk module into your python program because this class is needed to create the Tkinter’s button.
from tkinter import ttk
Below is the entire Tkinter program used to create the Tkinter Button and the function which will be called by the button if the user has clicked on that particular button.
import tkinter as tk from tkinter import ttk win = tk.Tk() win.title("Hello World!") def showHello(txt): hello.configure(text=txt) # change the text inside the button hello = ttk.Button(win, text="Hello!", command=lambda: showHello("Hello Again")) hello.grid(column=0, row=0) win.mainloop()
The program starts as follows:
After the user has clicked on the button the text within that button will get replaced by the showHello function as follows:
So do you think Tkinter is simple and easy to learn? Leave your comment below this post!