Tkinter GUI Application Development Cookbook
eBook - ePub

Tkinter GUI Application Development Cookbook

  1. 242 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Tkinter GUI Application Development Cookbook

Book details
Book preview
Table of contents
Citations

About This Book

Discover solutions to all your Tkinter and Python GUI development problemsAbout This Book• Integrate efficient Python GUI programming techniques with Tkinter• Efficiently implement advanced MVC architectures in your Python GUI apps• Solve all your problems related to Tkinter and Python GUI developmentWho This Book Is ForThis book is for Python developers who are familiar with the basics of the language syntax, data structures, and OOP. You do not need previous experience with Tkinter or other GUI development libraries.What You Will Learn• Add widgets and handle user events• Lay out widgets within windows using frames and the different geometry managers• Configure widgets so that they have a customized appearance and behavior• Improve the navigation of your apps with menus and dialogs• Apply object-oriented programming techniques in Tkinter applications• Use threads to achieve responsiveness and update the GUI• Explore the capabilities of the canvas widget and the types of items that can be added to it• Extend Tkinter applications with the TTK (themed Tkinter) moduleIn DetailAs one of the more versatile programming languages, Python is well-known for its batteries-included philosophy, which includes a rich set of modules in its standard library; Tkinter is the library included for building desktop applications. Due to this, Tkinter is a common choice for rapid GUI development, and more complex applications can benefit from the full capabilities of this library. This book covers all of your Tkinter and Python GUI development problems and solutions.Tkinter GUI Application Development Cookbook starts with an overview of Tkinter classes and at the same time provides recipes for basic topics, such as layout patterns and event handling. Next, we cover how to develop common GUI patterns, such as entering and saving data, navigating through menus and dialogs, and performing long-running actions in the background. You will then make your apps leverage network resources effectively, perform 2D and 3D animation-related tasks, create 3D objects, and perform advanced graphical operations. Finally, this book covers using the canvas and themed widgets.By the end of the book, you will have an in-depth knowledge of Tkinter classes, and will know how to use them to build efficient and rich GUI applications.Style and approachA practical recipe-based guide that will help you find solutions to all your Tkinter and Python GUI development-related problems.

Frequently asked questions

Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes, you can access Tkinter GUI Application Development Cookbook by Alejandro Rodas de Paz in PDF and/or ePUB format, as well as other popular books in Computer Science & Web Development. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788627771
Edition
1

Canvas and Graphics

In this chapter, we will cover the following recipes:
  • Understanding the coordinate system
  • Drawing lines and arrows
  • Writing text on a canvas
  • Adding shapes to the canvas
  • Finding items by their position
  • Moving canvas items
  • Detecting collisions between items
  • Deleting items from a canvas
  • Binding events to canvas items
  • Rendering a canvas into a PostScript file

Introduction

In the first chapter, we covered several recipes for the standard Tkinter widget. However, we skipped the Canvas widget because it offers plenty of graphical capabilities, and it deserves a dedicated chapter by itself to dive into its common use cases.
A canvas is a rectangular area where you can not only display text and geometric shapes, such as lines, rectangles, or ovals, but also nest other Tkinter widgets. These objects are called canvas items, and each one has a unique identifier that allows us to manipulate them before they are initially displayed on the canvas.
We will cover the methods of the Canvas class with interactive samples, which will help us to identify frequent patterns that could be translated to the applications we want to build.

Understanding the coordinate system

To draw graphic items on a canvas, we will need to specify their position using a coordinate system. Since a canvas is a two-dimensional space, points will be notated by their coordinates on the horizontal and vertical axes—commonly labeled x and y respectively.
With a simple application, we can easily illustrate how to locate these points in relation to the origin of the coordinate system, placed in the upper-left corner of the canvas area.

How to do it...

The following program contains an empty canvas and a label that shows the location of the cursor on the canvas; you can move the cursor to see what position it is placed in, giving clear feedback on how the x and y coordinates increment or decrement, depending on the direction you move the mouse pointer:
import tkinter as tk

class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Basic canvas")

self.canvas = tk.Canvas(self, bg="white")
self.label = tk.Label(self)
self.canvas.bind("<Motion>", self.mouse_motion)

self.canvas.pack()
self.label.pack()

def mouse_motion(self, event):
x, y = event.x, event.y
text = "Mouse position: ({}, {})".format(x, y)
self.label.config(text=text)

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

How it works...

The Canvas instance is created like any other Tkinter widget, that is, by first passing the parent container and the additional configuration options as keyword arguments:
 def __init__(self):
# ...
self.canvas = tk.Canvas(self, bg="white")
self.label = tk.Label(self)
self.canvas.bind("<Motion>", self.mouse_motion)
The next screenshot shows a point composed of the perpendicular projections of each axis:
  • The x coordinate corresponds to the distance on the horizontal axis and increments its value when you move the cursor from left to right
  • The y coordinate is the distance on the vertical axis and increments its value when you move the cursor from up to down
As you might have noticed in the preceding screenshot, these coordinates directly map to the x and y attributes of the event instance passed to the handler:
 def mouse_motion(self, event):
x, y = event.x, event.y
text = "Mouse position: ({}, {})".format(x, y)
self.label.config(text=text)
This happens because these attributes are calculated in respect to the widget that the event is bound to, in this case, the <Motion> sequence.

There's more...

The canvas surface can also display items with negative values in their coordinates. Depending on the item size, they can be partially shown on the top or left borders of the canvas.
In a similar way, if an item is placed at a point where any of its coordinates is greater than the canvas size, it may partially fall outside the bottom or right borders.

Drawing lines and arrows

One of the most basic actions you can perform with a canvas is drawing segments from one point to another. Although it is possible to directly draw polygons using other methods, the create_line method of the Canvas class has enough options to understand the basics of displaying items.

Getting ready

In this recipe, we will build an application that allows us to draw lines by clicking on the canvas. Each line will be displayed by clicking first on the point that will determine the line start, and a second time to set the line end.
We will be also able to specify some appearance options, such as color and width:

How to do it...

Our App class will be responsible for creating an empty canvas and handling mouse click events.
The information on the line options will be retrieved from the LineForm class. The approach of separating this component into a different class helps us to abstract its implementation details and focus on how to work with the Canvas widget.
For the sake of brevity, we omit the implementation of the LineForm class in the following snippet:
import tkinter as tk

class LineForm(tk.LabelFrame):
# ...

class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Basic canvas")

self.line_start = None
self.form = LineForm(self)
self.canvas = tk.Canvas(self, bg="white")
self.canvas.bind("<Button-1>", self.draw)

self.form.pack(side=tk.LEFT, padx=10, pady=10)
self.canvas.pack(side=tk.LEFT)

def draw(self, event):
x, y = event.x, event.y
if not self.line_start:
self.line_start = (x, y)
else:
x_origin, y_origin = self.line_start
self.line_start = None
line = (x_origin, y_origin, x, y)
arrow = self.form.get_arrow()
color = self.form.get_color()
width = self.form.get_width()
self.canvas.create_line(*line, arrow=arrow,
fill=color, width=width)

if __name__ == "__main__":
app = App()
app.mainloop()
You can find the complete code sample in the chapter7_02.py file.

How it works...

Since we want to handle the mouse clicks on the canvas, we w...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. Packt Upsell
  5. Contributors
  6. Preface
  7. Getting Started with Tkinter
  8. Window Layout
  9. Customizing Widgets
  10. Dialogs and Menus
  11. Object-Oriented Programming and MVC
  12. Asynchronous Programming
  13. Canvas and Graphics
  14. Themed Widgets
  15. Other Books You May Enjoy