Top 5 Python GUI libraries

Top 5 Python GUI libraries




There are a number of Python Graphical User Interfaces (GUIs). As the landscape continues to evolve, several libraries stand out for their ease of use, flexibility, and integration with modern technologies. This post will explore five Top  Python GUI libraries, demonstrating both simple and advanced examples to showcase their potential.

1. PyQt6

PyQt6 is a set of Python bindings for the Qt application framework. It’s widely used for creating cross-platform applications and provides many tools for managing UI, events, and more. PyQt6 is versatile, allowing developers to create anything from simple dialog boxes to complex, multi-threaded applications. Though this is not a detailed PyQt6 tutorial we shall discuss PyQt6 examples to have a better view of PyQT6

 

Creating a basic window with a button.

import sys
from
PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout

def on_click():
   
print("Button clicked!")
app = QApplication(sys.argv)

window = QWidget()
window.setWindowTitle('Simple PyQt6 Example')

layout = QVBoxLayout()
button = QPushButton('Click Me')
button.clicked.connect(on_click)

layout.addWidget(button)
window.setLayout(layout)
window.show()

sys.exit(app.
exec())

Detailed explanation of the PyQt6 code:

1. Importing Required Modules

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout

- sys: This module is imported to handle system-level functions like exiting the application.

- Then from PyQt6.QtWidgets QApplication, QWidget and QPushButton is imported

- QApplication: Manages application-wide resources and is required to create any PyQt6 application. It handles the event loop, which manages user interaction.

- QWidget: This is the base class for all PyQt6 GUI objects. It provides a window or container for other widgets (like buttons).

- QPushButton: A widget representing a clickable button.

- QVBoxLayout: A layout manager that arranges widgets vertically in a container. Layout managers control the placement and resizing of widgets.

2. Defining the Button Click Function

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

- This function will be called when the button is clicked. It prints a message `"Button clicked!"` to the console.

- It doesn't take any arguments or return any values; it's just a simple callback for demonstration purposes.

3. Creating the QApplication Object

app = QApplication(sys.argv)

- Every PyQt application must have a `QApplication` object, which is responsible for managing application-wide settings and resources. It processes and dispatches all events, like user inputs (mouse clicks, keypresses, etc.).

- `sys.argv` is passed to `QApplication` to handle command-line arguments that might be used when starting the application.

4. Setting Up the Main Window

window = QWidget()
window.setWindowTitle('Simple PyQt6 Example')

- window = QWidget(): This creates a window (or widget) using the `QWidget` class. This window will serve as the main interface where other components (like buttons) will be placed.

- window.setWindowTitle('Simple PyQt6 Example'): Sets the title of the window, which appears at the top when the window is displayed.

5. Creating a Layout and Adding Widgets

layout = QVBoxLayout()
button = QPushButton('Click Me')
button.clicked.connect(on_click)

- layout = QVBoxLayout(): Creates a vertical layout that will arrange widgets from top to bottom. PyQt layouts help manage the positioning of widgets in a container.

- button = QPushButton('Click Me'): Creates a button with the label "Click Me".

- button.clicked.connect(on_click): This connects the button's `clicked` signal to the `on_click` function. When the button is clicked, the `on_click` function is executed, printing "Button clicked!" in the console.

6. Adding the Button to the Layout

layout.addWidget(button)

- Adds the button to the vertical layout. It ensures that the button will be arranged vertically with other widgets (if any).

7. Setting the Layout to the Window

window.setLayout(layout)

- This assigns the layout (with the button inside it) to the `window`. Without this, the window would be empty. The layout manages the positioning and resizing of the button.

8. Displaying the Window

window.show()

- Displays the window along with its contents (the button in this case). Without calling `show()`, the window would not be visible to the user.

9. Starting the Event Loop

sys.exit(app.exec())

- app.exec(): Enters the event loop where the application will wait for user interaction (like button clicks or window closing). It handles events and updates the GUI accordingly.

- sys.exit(): Ensures that the program exits cleanly once the event loop is finished (when the window is closed). The `app.exec()` returns an exit code, which is passed to `sys.exit()`.

How It Works Together:

1. The code creates a simple window (`QWidget`) with a button labeled "Click Me".

2. When the button is clicked, the `on_click` function is called, printing "Button clicked!" to the console.

3. The window is displayed on the screen using the `window.show()` method.

4. The `QApplication` object (`app`) handles events and keeps the application running until the user closes the window, at which point the program exits cleanly.

This is a basic PyQt6 example showing how to create a window, add a button, and handle button clicks with minimal code.

 

A PyQt6-based text editor with file handling capabilities.

import sys
from
PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QFileDialog, QAction
from
PyQt6.QtCore import Qt

class TextEditor(QMainWindow):
   
def __init__(self):
       
super().__init__()
       
self.setWindowTitle("Advanced PyQt6 Text Editor")
       
self.editor = QTextEdit(self)
       
self.setCentralWidget(self.editor)
       
self.create_menu()

   
def create_menu(self):
       menu =
self.menuBar().addMenu("File")
       
       open_action = QAction(
"Open", self)
       open_action.triggered.connect(
self.open_file)
       menu.addAction(open_action)

       save_action = QAction(
"Save", self)
       save_action.triggered.connect(
self.save_file)
       menu.addAction(save_action)

   
def open_file(self):
       file_path,
_ = QFileDialog.getOpenFileName(self, "Open File", "", "Text Files (*.txt)")
       
if file_path:
           with open(file_path,
'r') as file:
               
self.editor.setText(file.read())

   
def save_file(self):
       file_path,
_ = QFileDialog.getSaveFileName(self, "Save File", "", "Text Files (*.txt)")
       
if file_path:
           with open(file_path,
'w') as file:
               file.write(
self.editor.toPlainText())

app = QApplication(sys.argv)
window = TextEditor()
window.show()

sys.exit(app.exec())

2. Tkinter (Python’s Standard GUI Library)

Tkinter is the default GUI toolkit in Python and is widely used for simple applications. It is easy to get started with and is perfect for building lightweight GUIs.

Creating a basic window with an entry field and a label.

import tkinter as tk

def show_input():
   label.config(
text="Hello " + entry.get())
root = tk.Tk()
root.title(
"Simple Tkinter Example")

entry = tk.Entry(root)
entry.pack()

button =
tk.Button(root, text="Submit", command=show_input)
button.pack()

label = tk.Label(root,
text="")
label.pack()

root.mainloop()

Detailed explanation of the provided Tkinter code:

1. Importing the Tkinter Module

import tkinter as tk

- tkinter: This module is Python's standard library for creating Graphical User Interfaces (GUIs).

- `tk`: The module is imported as `tk` for convenience, allowing you to reference it using `tk.` when calling its functions and classes.

2. Defining the Function to Handle Button Click

def show_input():
   label.
config(text="Hello " + entry.get())

- show_input: This function is executed when the button is clicked.

- entry.get(): Retrieves the text that the user has typed into the entry widget.

- label.config(text="Hello " + entry.get()): Updates the text of the `label` to display `"Hello "` followed by the text from the entry field.

 

3. Creating the Main Window

root = tk.Tk()
root.title(
"Simple Tkinter Example")

- root = tk.Tk(): This line initializes the main window. `Tk()` creates the application’s main window, known as the root window.

- root.title("Simple Tkinter Example"): Sets the title of the window to "Simple Tkinter Example", which appears at the top of the window.

4. Adding an Entry Widget

entry = tk.Entry(root)
entry.pack()

- entry = tk.Entry(root): Creates an entry widget, which allows the user to input text. The `Entry` widget is placed inside the `root` window.

- entry.pack(): The `pack()` method is used to arrange the widget in the window. It tells Tkinter to place the entry widget in the root window using a simple layout manager.

5. Adding a Button

button = tk.Button(root, text="Submit", command=show_input)
button.pack()

- button = tk.Button(root, text="Submit", command=show_input)`**: This creates a button with the label "Submit". The `command=show_input` specifies that when the button is clicked, the `show_input` function should be executed.

- button.pack(): Again, the `pack()` method is used to place the button in the window. It automatically positions the button below the entry widget.

6. Adding a Label

label = tk.Label(root, text="")
label.pack()

- label = tk.Label(root, text=""): Creates a label widget with an empty text string (`""`). The label is used to display the result after the button is clicked.

- label.pack(): The `pack()` method is used to place the label in the window, just below the button.

7. Running the Event Loop

root.mainloop()

- root.mainloop(): This starts the Tkinter event loop, which keeps the window open and responsive to user input (e.g., button clicks). The loop runs until the user closes the window.

How It Works:

1. The program creates a simple window (`root`).

2. An entry field (`entry`) allows the user to type text.

3. When the "Submit" button is clicked, the text from the entry is retrieved, and the `show_input` function updates the `label` to display "Hello " followed by the entered text.

4. The label starts with an empty string and is updated with the user's input once the button is clicked.

5. The program runs continuously using the `mainloop()` function, which keeps the window open and handles user events until it is closed.

This code provides a basic example of Tkinter’s functionality, demonstrating how to create a window with an entry field, a button, and a label, and how to handle user input interactively.

A multi-window application with dynamic content switching.

import tkinter as tk

class MainApp(tk.Tk):
   
def __init__(self):
       
super().__init__()
       
self.title("Advanced Tkinter Example")
       
self.geometry("400x200")
       
       
self.button_frame = tk.Frame(self)
       
self.button_frame.pack()

       
self.label = tk.Label(self, text="Welcome", font=("Arial", 18))
       
self.label.pack()

       btn1 = tk.Button(
self.button_frame, text="Open Window 1", command=self.open_window1)
       btn2 = tk.Button(
self.button_frame, text="Open Window 2", command=self.open_window2)
       btn1.pack(side=
"left", padx=20)
       btn2.pack(side=
"left", padx=20)

   
def open_window1(self):
       
self.label.config(text="This is Window 1")

   
def open_window2(self):
       
self.label.config(text="This is Window 2")

if __name__ == "__main__":
   app = MainApp()
   app.mainloop()

3. Kivy

Open Source Python Library

Kivy is an open-source Python library for rapid development of applications that use innovative user interfaces, such as multi-touch apps. Kivy is highly efficient and supports mobile app development as well.

How to use Graphic Designer of Python Kivy

from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
   
def build(self):
       
return Button(text="Hello Kivy")

if __name__ == '__main__':
   MyApp().run()

A Kivy-based calculator with dynamic layouts.

import tkinter as tk

def show_input():
   label.config(
text="Hello " + entry.get())

root = tk.Tk()
root.title(
"Simple Tkinter Example")

entry = tk.Entry(root)
entry.pack()

button = tk.Button(root,
text="Submit", command=show_input)
button.pack()

label = tk.Label(root,
text="")
label.pack()

root.mainloop()


       
return layout

   def on_button_press(self, instance):
       
if instance.text == "=":
           
try:
               self.
result.text = str(eval(self.result.text))
           except Exception:
               self.
result.text = "Error"
       
else:
           self.
result.text += instance.text

if __name__ == '__main__':
   CalculatorApp().run()

4. Dear PyGui

Dear PyGui is a fast, powerful, GPU-accelerated Python GUI framework built for modern user interfaces. It’s based on Dear ImGui, which provides immediate-mode graphical APIs.

Creating a window with buttons and a basic plot.

import dearpygui.dearpygui as dpg

dpg.create_context()

with
dpg.window(label="Simple Dear PyGui Example"):
   dpg.add_button(
label="Click Me")
   dpg.add_text(
"Hello, Dear PyGui!")

dpg.create_viewport(
title="Dear PyGui Example", width=600, height=400)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()

An interactive
 graphing tool with Dear PyGui.

import
dearpygui.dearpygui as dpg
import numpy as np

dpg.create_context()

def plot_data(sender, app_data):
   x = np.linspace(0, 10, 100)
   y = np.sin(x)
   dpg.delete_item(
"plot_series")
   dpg.add_line_series(x, y,
label="Sine Wave", parent="plot", tag="plot_series")

with
dpg.window(label="Advanced Dear PyGui Example"):
   dpg.add_button(
label="Generate Plot", callback=plot_data)
   with dpg.plot(
label="Sine Wave Plot", tag="plot"):
       dpg.add_plot_legend()
       dpg.add_plot_axis(dpg.mvXAxis,
label="X-Axis")
       dpg.add_plot_axis(dpg.mvYAxis,
label="Y-Axis", tag="y_axis")

dpg.create_viewport(
title="Dear PyGui Advanced Example", width=800, height=600)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()

 How to use Graphic Designer of Python Dear PyGui

Dear PyGui example

import dearpygui.dearpygui as dpg

- dearpygui.dearpygui: This module provides the functionality for creating graphical interfaces using Dear PyGui.

- dpg: It is imported as `dpg` for convenience, allowing you to reference the Dear PyGui API using the `dpg.` prefix.

Creating a Dear PyGui Context
dpg.create_context()

- This initializes the Dear PyGui context, which is necessary for using any of the Dear PyGui features. This is equivalent to starting up the environment where GUI elements can be created and managed.

 

3. Defining a Window

with dpg.window(label="Simple Dear PyGui Example"):
   dpg.add_button(
label="Click Me")
   dpg.add_text(
"Hello, Dear PyGui!")

- with dpg.window(label="Simple Dear PyGui Example"):: This block creates a window in the GUI. The label of the window is set to `"Simple Dear PyGui Example"`. Everything inside this `with` block will be added as child elements (widgets) to this window.

 

- dpg.add_button(label="Click Me"): This creates a button inside the window with the label "Click Me". By default, the button does nothing when clicked since no callback is assigned here.

- dpg.add_text("Hello, Dear PyGui!"): This adds a text widget to the window, displaying the message `"Hello, Dear PyGui!"`. It simply renders this static text within the window.

4. Creating the Viewport

dpg.create_viewport(title="Dear PyGui Example", width=600, height=400)

- dpg.create_viewport: This function creates a viewport (a window managed by the OS) where the GUI will be rendered. The viewport acts as the main application window that holds all the GUI elements.

 

- title="Dear PyGui Example: This sets the title of the viewport, which will appear at the top of the window.

 

- width=600, height=400: These define the dimensions (600 pixels wide and 400 pixels high) of the viewport.

5. Setting up Dear PyGui

dpg.setup_dearpygui()

- This function performs the necessary internal setup for Dear PyGui before starting the GUI event loop. It prepares the context and the viewport to be used.

6. Showing the Viewport

dpg.show_viewport()

- This makes the viewport (window) visible. Without calling this, the viewport would not be shown, and the user wouldn't see the window.

7. Running the Event Loop

dpg.start_dearpygui()

- dpg.start_dearpygui(): This enters Dear PyGui's event loop, which keeps the application running, manages user interaction (like button clicks), and renders the GUI continuously. This function must be called to keep the GUI responsive and active.

8. Cleaning Up

dpg.destroy_context()

- dpg.destroy_context()`: Once the event loop finishes (usually when the user closes the window), this function is called to clean up and destroy the Dear PyGui context, ensuring the program exits cleanly.

How Dear PyGui Works :

1. Creating the Context: The context is initialized with `dpg.create_context()`, allowing the program to build and manage the GUI.

2. Defining a Window: Inside the window, a button with the label "Click Me" and a text widget displaying "Hello, Dear PyGui!" are added.

3. Viewport Setup: A viewport (main window) is created with specific dimensions and title, and it is set up and shown using `dpg.setup_dearpygui()` and `dpg.show_viewport()`.

4. Event Loop: The program enters the Dear PyGui event loop (`dpg.start_dearpygui()`), which keeps the application running and responsive to user interactions.

5. Cleanup: Once the window is closed, the Dear PyGui context is destroyed using `dpg.destroy_context()` to ensure a clean exit.

This code demonstrates how to create a simple GUI using Dear PyGui, including a window, a button, and some text, while managing the lifecycle of the application.

5. PySide6 example and tutorial

How to use graphic designer Python Pyside6

PySide6 is the official set of Python bindings for Qt libraries, similar to PyQt. It is particularly effective for developing large-scale and highly responsive applications with sophisticated UI designs.

A basic PySide6 window with a label and button.

import sys
from PySide6.QtWidgets import QApplication, QPushButton, QLabel, QVBoxLayout, QWidget

def on_click():
   label.setText(
"Button clicked!")

app = QApplication(sys.argv)

window = QWidget()
layout = QVBoxLayout()

label = QLabel(
"Simple PySide6 Example")
button = QPushButton("Click Me")
button.clicked.connect(on_click)

layout.addWidget(label)
layout.addWidget(button)

window.setLayout(layout)
window.show()
sys.exit(app.
exec())

```

 

A PySide6 file explorer with folder navigation.

import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QTextEdit, QAction

class FileExplorer(QMainWindow):
   
def __init__(self):
       
super().__init__()
       
self.setWindowTitle("Advanced PySide6 File Explorer")
       
self.editor = QTextEdit(self)
       
self.setCentralWidget(self.editor)
       
self.create_menu()

   
def create_menu(self):
       menu =
self.menuBar().addMenu("File")
       
       open_action = QAction(
"Open", self)
       open_action.triggered.connect(
self.open_file)
       menu.addAction(open_action)

       save_action = QAction(
"Save", self)
       save_action.triggered.connect(
self.save_file)
       menu.addAction(save_action)

   
def open_file(self):
       file_path,
_ = QFileDialog.getOpenFileName(self, "Open File", "", "Text Files (*.txt)")
       
if file_path:
           with open(file_path,
'r') as file:
               
self.editor.setText(file.read())

   
def save_file(self):
       file_path,
_ = QFileDialog.getSaveFileName(self, "Save File", "", "Text Files (*.txt)")
       
if file_path:
           with open(file_path,
'w') as file:
               file.write(
self.editor.toPlainText())

if __name__ == "__main__":
   app = QApplication(sys.argv)
   window = FileExplorer()
   window.show()
   sys.exit(app.exec())

These are some of the Best Python GUI libraries. The above discussion covers Python PyQt6 examples, Python Tkinter examples, Python Kivy examples, Python Dear PyGui tutorials, Python Pyside6 examples and are top Python Graphic Design frameworks of 2024

No comments:

Post a Comment