Lesson 1: Starting with Tkinter in Python

Posted by

In this tutorial, we will be exploring how to use the tkinter library in Python to create graphical user interfaces (GUI) for our applications. Tkinter is a powerful module that comes pre-installed with Python and provides a simple way to create windows, dialog boxes, buttons, menus, and other GUI components.

To get started with tkinter, let’s first create a simple window using the following code:

<!DOCTYPE html>
<html>
<head>
    <title>My First Tkinter Window</title>
</head>
<body>
    <h1>My First Tkinter Window</h1>
    <script>
        import tkinter as tk

        # Create the main window
        root = tk.Tk()
        root.title("Hello, Tkinter!")

        # Add a label to the window
        label = tk.Label(root, text="Hello, World!")
        label.pack()

        # Start the main loop
        root.mainloop()
    </script>
</body>
</html>

In this code snippet, we first import the tkinter module as tk. Then, we create a main window using the Tk() function and set the title of the window using the title() method. Next, we create a label with the text "Hello, World!" and add it to the window using the pack() method. Finally, we start the main event loop using the mainloop() method.

When you run this code, you should see a simple window with a label that displays "Hello, World!". You can customize the window by changing the title, the text of the label, the font size, and other properties.

Next, let’s add a button to the window that will change the text of the label when clicked. Here’s the updated code:

<!DOCTYPE html>
<html>
<head>
    <title>My Tkinter Window with Button</title>
</head>
<body>
    <h1>My Tkinter Window with Button</h1>
    <script>
        import tkinter as tk

        # Function that changes the text of the label
        def on_click():
            label.config(text="Button Clicked!")

        # Create the main window
        root = tk.Tk()
        root.title("Hello, Tkinter!")

        # Add a label to the window
        label = tk.Label(root, text="Hello, World!")
        label.pack()

        # Add a button to the window
        button = tk.Button(root, text="Click Me", command=on_click)
        button.pack()

        # Start the main loop
        root.mainloop()
    </script>
</body>
</html>

In this code snippet, we define a function on_click() that changes the text of the label to "Button Clicked!". We then create a button with the text "Click Me" and associate it with the on_click() function using the command parameter. When you run this code, you should see a button that changes the label text when clicked.

This is just a basic introduction to tkinter in Python. You can explore more features and components of tkinter to create more complex and interactive GUIs for your applications. Happy coding!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@abualialhrerat9737
3 months ago

❤❤❤