A simple GUI app in Python and Tkinter

Problem

You wish to build a graphical user interface (GUI) application using Python. There is a library available for that; Tkinter. In this tutorial we will be using Python version 3.

Check it by running the following:

python3 -m tkinter

The output will be a small GUI app as follows:

a little gui program

In this tutorial we will design a simple GUI app that will show a button and when we click the button, prints in the console “Bye” and exits the application.

The code is as follows:

import tkinter as tk


class HelloWindow(tk.Tk):

    def greet(self):
        print("Bye")
        self.destroy()

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("Hello Window GUI app")
        btn_hello = tk.Button(self, fg="red", text="Bye", command=self.greet)
        btn_hello.pack(side=tk.TOP)


if __name__ == "__main__":
    app = HelloWindow()
    app.geometry("250x75")
    app.mainloop()

The code uses a class and the tk which is an alias for the loaded Tkinter library. The class has the __init__ method that simply sets the title of the window bar and then it creates a button named btn_hello with some properties. The button references the greet function using the command parameter. The greet function prints “Bye” and then quits the app.

Running it
python3 hello_window.py

It should show

Click the button to quit.

Conclusion

This was a very simple GUI application in Python using Tkinter. Programming GUI applications require a different approach well known as event-driven. In event-driven programming the program has events, e.g. a user clicks a button or types something in a text box, etc. Then a corresponding action executes. All this idea of user-event -> action and so forth is repeated (looping) as shown in the main[1] section (last line).

References


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x