Python Tkinter GUI Tutorial #1: Build Your First Desktop App Easily

Python, with its simplicity and extensive library support, is a popular choice for both server-side and GUI applications. When it comes to creating desktop applications, Python provides several options, but Tkinter is often the go-to library due to its ease of use and the fact that it comes bundled with Python. In this comprehensive guide, we'll explore Tkinter, Python's de-facto standard GUI (Graphical User Interface) package, and create a simple GUI application together.

Python GUI with Tkinter - 9 - Creating Drop Down Menus
Python GUI with Tkinter - 9 - Creating Drop Down Menus

Before we dive into Tkinter, let's ensure you have it installed. If you're using Python 3, Tkinter is typically pre-installed. However, if you're using an older version of Python or need to install it separately, you can do so using pip:

| Pythonista Planet
| Pythonista Planet

```python pip install tk ```

Setting Up Your Development Environment

For this tutorial, we'll need a simple text editor or Integrated Development Environment (IDE). You can use a simple text editor like Notepad++ or Visual Studio Code, or a full-blown IDE like PyCharm or IDLE (Python's built-in GUI).

How to Program a GUI Application (with Python Tkinter)!
How to Program a GUI Application (with Python Tkinter)!

For the sake of simplicity, we'll use IDLE for this guide. Here's how you can launch IDLE and create a new file:

  • Press Windows key + R to open the Run dialog box.
  • Type ` idle` and press Enter.
  • In IDLE, go to File > New File.
Tkinter GUI: Complete Guide with PythonGUI
Tkinter GUI: Complete Guide with PythonGUI

Python and Tkinter Installation Checks

Let's start by confirming that Tkinter is properly installed. Add the following code to your new file and click the 'Run' button (or press F5):

```python import tkinter as tk print("Tkinter Version:", tk.__version__) ```

The output should display the version of Tkinter, indicating a successful installation.

Create a GUI app with Tkinter - Step by Step Tutorial
Create a GUI app with Tkinter - Step by Step Tutorial

Creating Your First Tkinter GUI

Now that we've confirmed Tkinter's presence, let's create our first GUI application. Replace the previous code with the following:

```python import tkinter as tk # Create the root (main) window root = tk.Tk() # Set the window title root.title("My First GUI") # Enter the main loop root.mainloop() ```

Save this code and run it. You should see a small, blank window titled 'My First GUI'. This window is our base, and we'll build upon it in subsequent sections.

Multiple Tabs in Tkinter - Python GUI Tutorial
Multiple Tabs in Tkinter - Python GUI Tutorial

Understanding and Customizing the Root Window

The root window, an instance of `Tk`, is the main application window in Tkinter. In the previous example, we created a root window and entered the main event loop, which manages all window events and idle time for the entire application.

How to Create a GUI in Python with Tkinter
How to Create a GUI in Python with Tkinter
Learn Tkinter in 20 Minutes
Learn Tkinter in 20 Minutes
Digital Clock Using Python - Tkinter - Python GUI Project Tutorial
Digital Clock Using Python - Tkinter - Python GUI Project Tutorial
Build Python Graphic User Interface (GUI) by Tkinter
Build Python Graphic User Interface (GUI) by Tkinter
Use a Drag & Drop Editor to Make Tkinter Python GUI Applications!
Use a Drag & Drop Editor to Make Tkinter Python GUI Applications!
Python tkinter Toolbox
Python tkinter Toolbox
Python Tkinter GUI Design Using ttkbootstrap - Complete Course
Python Tkinter GUI Design Using ttkbootstrap - Complete Course
Registration Form Using Tkinter in Python with Source Code
Registration Form Using Tkinter in Python with Source Code
Basics of a Tkinter GUI
Basics of a Tkinter GUI

Tkinter uses a widget hierarchy, with the root window at the top. Other widgets, like buttons, labels, and frames, are part of this hierarchy and are created as instances of Tkinter classes. They can be arranged using geometry managers and packers to create complex, responsive layouts.

Setting Root Window Properties

Let's customize our root window. Add the following lines before the `mainloop()` call:

```python # Set the window size root.geometry("300x200") # width x height # Set the window resizability root.resizable(True, True) # Allow both width and height resizing # Set the window icon root.iconbitmap("icon.ico") # Use an .ico file # Set the window transparency root.attributes("-alpha", 0.9) # Change the window's transparency (0.0 - 1.0) ```

To use an .ico file, you can create or find one and save it in the same directory as your Python script. The other properties are self-explanatory and can be adjusted according to your needs.

Setting Root Window Behavior

There are numerous attributes you can set to control the behavior of your window. For example, you can:

  • Make the window Always-on-Top with `root.attributes("-topmost", True)`.
  • Enable full-screen mode with `root.attributes("-fullscreen", True)`.
  • Disable window resizing with `root.resizable(False, False)`.

To learn more about these attributes, refer to this reference.

Adding Widgets to Your GUI

Widgets are the building blocks of your GUI, allowing users to interact with your application. Tkinter provides numerous widgets, and we'll explore some of the most common ones in this section.

To add a widget to your GUI, you create an instance of the desired widget and pack/place/grid it within the root window or another widget. For simplicity, we'll use the `pack()` method in this tutorial. This method arranges widgets in blocks along the sides of the parent widget.

Labels

Labels are non-editable text widgets. They are useful for displaying information to the user. Here's how you can add a label to your window:

```python # Create a label widget label = tk.Label(root, text="Hello, Tkinter!") # Pack the label widget into the window label.pack() ```

The label's text can be changed at any time using the `configure()` method or by directly assigning a new value to the `text` attribute.

Buttons

Buttons are clickable widgets that trigger an action when clicked. Here's how you can create a simple button:

```python # Create a button widget with a command to quit the application quit_button = tk.Button(root, text="Quit", command=root.quit) # Pack the button widget into the window quit_button.pack() ```

In this example, clicking the "Quit" button will call `root.quit()`, closing the application's main window and exiting the main event loop.

Entries

Entries are single-line text input fields. Users can enter text into entries, and the contents can be retrieved with the `get()` method. Here's an example:

```python # Create an entry widget input_field = tk.Entry(root) # Pack the entry widget into the window input_field.pack() # Insert some initial text into the entry input_field.insert(0, "Enter text here...") ```

To retrieve the text entered by the user, use `input_field.get()`.

Creating Interactive GUI Applications

So far, we've created static GUIs with limited interactivity. Let's make our application more dynamic by adding event handling and user input processing.

In Tkinter, events are handled by binding functions to specific event types. For example, to handle a button click, you would bind a function to the `` event, which is triggered when the left mouse button is pressed:

```python # Create a button widget with an empty command (to be filled later) greet_button = tk.Button(root, text="Greet", command=None) # Pack the button widget into the window greet_button.pack() # Define a function to handle the button's click event def greet(): print("Hello, Tkinter!") # Perform some action here # Bind the greet function to the button's click event greet_button.config(command=greet) ```

User Input and Output

To create a more engaging application, let's modify our previous example to greet the user with their input. First, add an entry widget and update the `greet()` function like this:

```python # ... (Previous code) # Create an entry widget user_input = tk.Entry(root) # Pack the entry widget into the window user_input.pack() # ... (Previous code) def greet(): # Get the user's input name = user_input.get() # Greet the user print(f"Hello, {name}!") ```

Now, when you enter text in the entry field and click the "Greet" button, the application will greet you with your input. To make the output more visible, let's add a text widget to display the greetings:

```python # Create a text widget to display output output = tk.Text(root, height=10, width=30) # Pack the text widget into the window output.pack() def greet(): # Get the user's input name = user_input.get() # Greet the user and display the greeting in the text widget print(f"Hello, {name}!") # Add the greeting to the text widget output.insert(tk.END, f"Hello, {name}!\n") ```

Now, whenever you enter text and click the "Greet" button, the application will greet you and display the greeting in the text widget.

putting It All Together

In this tutorial, we've explored the basics of Tkinter and created a simple interactive GUI application. You've learned how to set up your development environment, create a root window, customize its properties, and add various widgets like labels, buttons, and entries.

Tkinter is a powerful library, and there's much more to explore. In subsequent tutorials, we'll delve into more advanced topics such as layouts, frames, canvas, list boxes, checkboxes, radio buttons, and bound variables. We'll also discuss event handling, regular expressions, and file dialogs.

For now, experiment with the examples provided in this guide and try creating your own GUIs. The official Tkinter documentation (https://docs.python.org/3/library/tk.html) is an invaluable resource for learning more about this library.

The journey of mastering Tkinter is filled with excitement and endless possibilities. Happy coding, and see you in the next tutorial!

Related Articles

Python Gpu Programming Example Raspberry Pi Python Programming Tutorial Python Programming Tutorial Python Programming Tutorialspoint Tutorial On Python Programming Python Programing Tutorials How To Tie A Bow Knot With One String Python Ai Programming Tutorial Pdf Python Programming Tutorial For Beginners Pdf How To Make Python Use Gpu