Learn Python TKinter GUI Programming with Code Tutorial

Posted by

Python GUI Tutorial | TKinter | Python | with Code

Python GUI Tutorial | TKinter | Python | with Code

In this tutorial, we will learn how to create a graphical user interface (GUI) using TKinter in Python. TKinter is the standard GUI toolkit for Python and provides a simple way to create windows, dialogs, buttons, menus, and other GUI elements.

Getting Started

First, make sure you have Python installed on your computer. You can download Python from the official website and follow the installation instructions. Once Python is installed, open a new file in your favorite text editor and save it with a .py extension.

Creating a Simple Window

Now, let’s create a simple window using TKinter. Add the following code to your .py file:


import tkinter as tk

# Create a new window
window = tk.Tk()

# Set the window title
window.title("Hello, TKinter!")

# Set the window size
window.geometry("400x300")

# Run the main loop
window.mainloop()

Save the file and run it using the command line. You should see a new window with the title “Hello, TKinter!” and a size of 400×300 pixels.

Adding Buttons and Labels

You can also add buttons and labels to your TKinter window. For example, you can add a button that prints a message when clicked:


import tkinter as tk

def on_button_click():
print("Button clicked!")

window = tk.Tk()
window.title("Hello, TKinter!")
window.geometry("400x300")

button = tk.Button(window, text="Click me!", command=on_button_click)
button.pack()

window.mainloop()

When you run this code, you will see a button with the text “Click me!” in the window. When you click the button, the message “Button clicked!” will be printed to the console.

Conclusion

TKinter is a powerful and easy-to-use GUI toolkit for Python. In this tutorial, we learned how to create a simple window and add buttons and labels to it. You can now explore more advanced features of TKinter and create your own custom GUI applications.