📜  Python GUI – PyQt VS TKinter(1)

📅  最后修改于: 2023-12-03 14:45:58.459000             🧑  作者: Mango

Python GUI - PyQt VS TKinter

GUI (Graphical User Interface) allows users to interact with programs using graphical elements such as buttons, menus, and text fields. Python provides two popular libraries for creating GUI applications: PyQt and Tkinter.

PyQt

PyQt is a set of Python bindings for the Qt application framework and runs on all platforms supported by Qt including Windows, OS X, Linux, iOS and Android. PyQt provides a wide range of widgets including buttons, labels, text boxes, tables, and many more. It also provides extensive documentation and tutorials to get started quickly.

# Example PyQt code:
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QVBoxLayout, QWidget

class Example(QWidget):
    def __init__(self):
        super().__init__()

        # Create widgets
        self.label = QLabel('Hello World!')
        self.button = QPushButton('Click me!')

        # Create layout & add widgets
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.button)

        # Set layout
        self.setLayout(layout)

app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
Tkinter

Tkinter is the standard Python interface to the Tk GUI toolkit. It is the most commonly used library for creating GUI applications in Python, and it comes bundled with Python installations on most platforms. Tkinter provides a wide range of widgets including buttons, labels, text boxes, and many more. It also provides extensive documentation and tutorials to get started quickly.

# Example Tkinter code:
import tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)

        # Create widgets
        self.label = tk.Label(self, text='Hello World!')
        self.button = tk.Button(self, text='Click me!', command=self.callback)

        # Create layout & add widgets
        self.label.pack()
        self.button.pack()

    def callback(self):
        print('Button clicked!')

root = tk.Tk()
ex = Example(root)
ex.pack()
root.mainloop()
Conclusion

Both PyQt and Tkinter are powerful GUI libraries that allow developers to easily create cross-platform desktop applications with Python. The choice between the two largely depends on personal preference and the specific requirements of the project. PyQt provides a wide range of widgets and has a more modern look and feel, while Tkinter is lightweight and comes built-in with Python installations. Whichever library you choose, there are plenty of resources available to help you get started.