How to Add Functions to Python Tkinter?

Recently in a webinar, someone asked me how to add functions to Python Tkinter for GUI applications, Then I explored more about how to add functions and in this tutorial, I will share my findings with suitable examples and screenshots.

Set Up the Tkinter GUI

First, let’s set up a basic Tkinter window for our application. We’ll create a simple interface with a label, entry field, and button:

import tkinter as tk

window = tk.Tk()
window.title("Customer Info")

name_label = tk.Label(window, text="Enter customer name:")
name_label.pack()

name_entry = tk.Entry(window)
name_entry.pack()

submit_button = tk.Button(window, text="Submit")
submit_button.pack()

window.mainloop()

This code creates a window titled “Customer Info” with a label prompting the user to enter a name, an entry field for inputting the name, and a submit button.

Read How to Use Tkinter Entry Widget in Python?

Define the Function

Next, let’s define the Python function that we want to call when the submit button is clicked. In this example, we’ll create a function that takes the entered customer name and displays a personalized greeting:

def greet_customer():
    name = name_entry.get()
    greeting = f"Hello, {name}! Welcome to our store."
    result_label.config(text=greeting)

The greet_customer() function retrieves the name entered in the name_entry field using the get() method. It then creates a personalized greeting string and updates the text of a result_label (which we’ll add to our GUI) to display the greeting.

Check out How to Create Checkboxes in Python Tkinter?

Connect the Function to the Button

To call the greet_customer() function when the submit button is clicked, we need to modify our button code:

submit_button = tk.Button(window, text="Submit", command=greet_customer)

By adding the command parameter and setting it to our greet_customer function (without parentheses), we tell Tkinter to call this function whenever the button is clicked.

Read How to Create and Customize Listboxes in Python Tkinter?

Display the Result

Finally, let’s add a label to our GUI to display the personalized greeting:

result_label = tk.Label(window, text="")
result_label.pack()

We create an empty label result_label and pack it into the window. The greet_customer() function will update the text of this label with the personalized greeting.

Read How to Create Checkboxes in Python Tkinter?

Complete Code

Here’s the complete code for our Tkinter GUI application with the added function:

import tkinter as tk

def greet_customer():
    name = name_entry.get()
    greeting = f"Hello, {name}! Welcome to our store."
    result_label.config(text=greeting)

window = tk.Tk()
window.title("Customer Info")

name_label = tk.Label(window, text="Enter customer name:")
name_label.pack()

name_entry = tk.Entry(window)
name_entry.pack()

submit_button = tk.Button(window, text="Submit", command=greet_customer)
submit_button.pack()

result_label = tk.Label(window, text="")
result_label.pack()

window.mainloop()

When you run this code, you’ll see a window with a label, entry field, and submit button. Enter a name (e.g., “John”) and click the submit button. The greet_customer() function will be called, and the personalized greeting (“Hello, John! Welcome to our store.”) will be displayed in the result_label.

You can see the output screen in the screenshot below.

Add Functions to Python Tkinter

Check out How to Create and Customize Listboxes in Python Tkinter?

Handle Real-World Issues

In real-world applications, you may encounter situations where you need to perform more complex tasks when a button is clicked. For example, let’s say you’re building a customer management system and need to validate the entered name before displaying the greeting. You can modify the greet_customer() function to handle this:

def greet_customer():
    name = name_entry.get()
    if name:
        greeting = f"Hello, {name}! Welcome to our store."
        result_label.config(text=greeting)
    else:
        result_label.config(text="Please enter a name.")

You can see the output screen in the screenshot below.

How to Add Functions to Python Tkinter

Now, if the user clicks the submit button without entering a name, the result_label will display “Please enter a name.” instead of a greeting.

Read How to Create Radio Buttons in Python with Tkinter?

Best Practices

When adding functions to your Tkinter GUI applications, keep the following best practices in mind:

  • Keep your functions focused and modular. Each function should have a specific purpose and be responsible for a single task.
  • Use descriptive names for your functions to improve code readability and maintainability.
  • Validate user input to ensure your functions receive the expected data and handle errors gracefully.
  • Separate the GUI code from the underlying business logic to make your code more maintainable and reusable.

Check out How to use Tkinter Filedialog in Python

Conclusion

In this tutorial, I have explained how to add functions to Python Tkinter for GUI applications. I discussed setting up the Tkinter GUI, defining a function, connecting the function to the button, and displaying the result. I also discussed how to handle real-world issues.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.