Python GUI Programming Cookbook
eBook - ePub

Python GUI Programming Cookbook

Develop functional and responsive user interfaces with tkinter and PyQt5, 3rd Edition

Burkhard Meier

  1. 486 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Python GUI Programming Cookbook

Develop functional and responsive user interfaces with tkinter and PyQt5, 3rd Edition

Burkhard Meier

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Over 90 recipes to help you develop widgets, forms, layouts, charts, and much more using the latest features of Python 3

Key Features

  • Use object-oriented programming to develop impressive GUIs in Python
  • Create interesting charts to visually represent data using Matplotlib
  • Develop GUIs with the latest versions of tkinter, PyQt5, and wxPython frameworks

Book Description

Python is a multi-domain, interpreted programming language that is easy to learn and implement. With its wide support for frameworks to develop GUIs, you can build interactive and beautiful GUI-based applications easily using Python. This third edition of Python GUI Programming Cookbook follows a task-based approach to help you create effective GUIs with the smallest amount of code. Every recipe in this book builds upon the last to create an entire, real-life GUI application. These recipes also help you solve problems that you might encounter while developing GUIs. This book mainly focuses on using Python's built-in tkinter GUI framework. You'll learn how to create GUIs in Python using simple programming styles and object-oriented programming (OOP). As you add more widgets and expand your GUI, you will learn how to connect to networks, databases, and graphical libraries that greatly enhance the functionality of your GUI. You'll also learn how to use threading to ensure that your GUI doesn't become unresponsive. Toward the end, you'll learn about the versatile PyQt GUI framework, which comes along with its own visual editor that allows you to design GUIs using drag and drop features. By the end of the book, you'll be an expert in designing Python GUIs and be able to develop a variety of GUI applications with ease.

What you will learn

  • Create amazing GUIs with Python's built-in tkinter module
  • Customize GUIs using layout managers to arrange GUI widgets
  • Advance from the typical waterfall coding style to an OOP style using Python
  • Develop beautiful charts using the free Matplotlib Python module
  • Use threading in a networked environment to make GUIs responsive
  • Discover ways to connect GUIs to a MySQL database
  • Understand how unit tests can be created and internationalize GUI
  • Delve into the world of GUI creation using PyQt5

Who this book is for

If you're a programmer or developer looking to enhance your Python skills by writing powerful GUI applications, this book is for you. Familiarity with the Python programming language is necessary to get the most out of the book.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Python GUI Programming Cookbook un PDF/ePUB en línea?
Sí, puedes acceder a Python GUI Programming Cookbook de Burkhard Meier en formato PDF o ePUB, así como a otros libros populares de Computer Science y Desktop Applications. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2019
ISBN
9781838828813
Edición
3

Best Practices

In this chapter, we will explore the different best practices that can help us to build our GUI efficiently and keep it both maintainable and extendable.
These best practices will also help you to debug your GUI to get it just the way you want it to be.
Here is the overview of Python modules for this chapter:
Knowing how to code using best practices will greatly enhance your Python programming skills.
The recipes that will be discussed in this chapter are the following:
    • Avoiding spaghetti code
    • Using __init__ to connect modules
    • Mixing fall-down and OOP coding
    • Using a code naming convention
    • When not to use OOP
    • How to use design patterns successfully
    • Avoiding complexity
    • GUI design using multiple notebooks

Avoiding spaghetti code

In this recipe, we will explore a typical way to create spaghetti code and then we will see a much better way of how to avoid such code.
Spaghetti code is code in which a lot of functionality is intertangled.

Getting ready

We will create a new, simple GUI, written in Python using the built-in Python tkinkter library.

How to do it...

Having searched online and read the documentation, we might start by writing the following code to create our GUI:
  1. Create a new module: GUI_Spaghetti.py.
  2. Add the following code:
# Spaghetti Code ############################# 
def PRINTME(me):print(me)
import tkinter
x=y=z=1
PRINTME(z)
from tkinter import *
scrolW=30;scrolH=6
win=tkinter.Tk()
if x:chVarUn=tkinter.IntVar()
from tkinter import ttk
WE='WE'
import tkinter.scrolledtext
outputFrame=tkinter.ttk.LabelFrame(win,text=' Type into the scrolled text control: ')
scr=tkinter.scrolledtext.ScrolledText(outputFrame,width=scrolW,height=scrolH,wrap=tkinter.WORD)
e='E'
scr.grid(column=1,row=1,sticky=WE)
outputFrame.grid(column=0,row=2,sticky=e,padx=8)
lFrame=None
if y:chck2=tkinter.Checkbutton(lFrame,text="Enabled",variable=chVarUn)
wE='WE'
if y==x:PRINTME(x)
lFrame=tkinter.ttk.LabelFrame(win,text="Spaghetti")
chck2.grid(column=1,row=4,sticky=tkinter.W,columnspan=3)
PRINTME(z)
lFrame.grid(column=0,row=0,sticky=wE,padx=10,pady=10)
chck2.select()
try: win.mainloop()
except:PRINTME(x)
chck2.deselect()
if y==x:PRINTME(x)
# End Pasta #############################
  1. Run the code and observe the output, as follows:

  1. Compare the preceding GUI to the intended GUI design, as follows:
  1. Create a new module, GUI_NOT_Spaghetti.py, and add the following code:
#====================== 
# imports
#======================
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
#======================
# Create instance
#======================
win = tk.Tk()
#======================
# Add a title
#======================
win.title("Python GUI")
#=========================
# Disable resizing the GUI
#=========================
win.resizable(0,0)

  1. Next, add some controls:
#============================================================= 
# Adding a LabelFrame, Textbox (Entry) and Combobox
#=============================================================
lFrame = ttk.LabelFrame(win, text="Python GUI Programming Cookbook")
lFrame.grid(column=0, row=0, sticky='WE', padx=10, pady=10)
#=============================================================
# Using a scrolled Text control
#=============================================================
outputFrame = ttk.LabelFrame(win, text=' Type into the scrolled text
control: ')
outputFrame.grid(column=0, row=2, sticky='E', padx=8)
scrolW = 30
scrolH = 6
scr = scrolledtext.ScrolledText(outputFrame, width=scrolW,
height=scrolH, wrap=tk.WORD)
scr.grid(column=1, row=0, sticky='WE')
  1. Add some more widgets:
#============================================================= 
# Creating a checkbutton
#=============================================================
chVarUn = tk.IntVar()
check2 = tk.Checkbutton(lFrame, text="Enabled", variable=chVarUn)
check2.deselect()
check2.grid(column=1, row=4, sticky=tk.W, columnspan=3)
#======================
# Start GUI
#======================
win.mainloop()
  1. Run the code and observe the following output:
Let's go behind the scenes to understand the code better.

How it works...

While the spaghetti code created a GUI, it is very hard to read because there is so much confusion in the code. Good code has many advantages over spaghetti code.
Let's see an example of spaghetti code first:
def PRINTME(me):print(me) 
import tkinter
x=y=z=1
PRINTME(z)
from tkinter import *
Now, consider this example good code (note that there is not much confusion in reading the code):
#====================== 
# imports
#======================
import tkinter as tk
from tkinter import ttk
The good code has a clearly commented section. We can easily find the import statements:
#-----------------------------------
Consider the following spaghetti code:
import tkinter.scrolledtext 
outputFrame=tkinter.ttk.LabelF...

Índice

Estilos de citas para Python GUI Programming Cookbook

APA 6 Citation

Meier, B. (2019). Python GUI Programming Cookbook (3rd ed.). Packt Publishing. Retrieved from https://www.perlego.com/book/1204143/python-gui-programming-cookbook-develop-functional-and-responsive-user-interfaces-with-tkinter-and-pyqt5-3rd-edition-pdf (Original work published 2019)

Chicago Citation

Meier, Burkhard. (2019) 2019. Python GUI Programming Cookbook. 3rd ed. Packt Publishing. https://www.perlego.com/book/1204143/python-gui-programming-cookbook-develop-functional-and-responsive-user-interfaces-with-tkinter-and-pyqt5-3rd-edition-pdf.

Harvard Citation

Meier, B. (2019) Python GUI Programming Cookbook. 3rd edn. Packt Publishing. Available at: https://www.perlego.com/book/1204143/python-gui-programming-cookbook-develop-functional-and-responsive-user-interfaces-with-tkinter-and-pyqt5-3rd-edition-pdf (Accessed: 14 October 2022).

MLA 7 Citation

Meier, Burkhard. Python GUI Programming Cookbook. 3rd ed. Packt Publishing, 2019. Web. 14 Oct. 2022.