Docsity

Tkinter by example 1, Apuntes de Ingeniería

Vista previa parcial del texto

¡Descarga Tkinter by example 1 y más Apuntes en PDF de Ingeniería solo en Docsity!

Python Tkinter By Example

David Love

January 18, 2018

Contents

  • 0.1 Introduction
  • 0.2 Who this book is aimed at
  • 0.3 How to get the most out of this book
  • 0.4 About tkinter
    • 0.4.1 Installing
    • 0.4.2 What is it anyway?
    • 0.4.3 Why write about tkinter?
    • 0.4.4 I heard tkinter is ugly
  • 1 Hello World
    • 1.1 Basic Example
    • 1.2 Using Classes
  • 2 A To-Do List
    • 2.1 A Basic List App
      • 2.1.1 init
      • 2.1.2 add_item
      • 2.1.3 Next Iteration
    • 2.2 Scrolling and Deleting
      • 2.2.1 Canvases and Frames
      • 2.2.2 init
      • 2.2.3 Handling Tasks
      • 2.2.4 Adjusting the canvas
      • 2.2.5 Mouse scrolling
      • 2.2.6 Next Iteration
    • 2.3 Permanent Storage
      • 2.3.1 runQuery
      • 2.3.2 firstTimeDb
      • 2.3.3 init
      • 2.3.4 add_task and remove_task
      • 2.3.5 save_task and load_tasks
      • 2.3.6 The final app
      • 2.3.7 Further Development
  • 3 A Multi-Language Translation Tool
    • 3.1 A Single-Translation Interface
      • 3.1.1 requests
      • 3.1.2 init
      • 3.1.3 translate
      • 3.1.4 copy_to_clipboard
      • 3.1.5 Next Iteration
    • 3.2 Three Tabs and a Menu
      • 3.2.1 init
      • 3.2.2 translate
  • CONTENTS - 3.2.3 add_portuguese_tab - 3.2.4 Next Iteration
    • 3.3 A Truly Dynamic App
      • 3.3.1 The LanguageTab
      • 3.3.2 The TranslateBook
      • 3.3.3 NewLanguageForm
      • 3.3.4 Running this version
      • 3.3.5 Further Development
  • 4 A Point-and-Click Game
    • 4.1 The Initial Concept
      • 4.1.1 GameScreen
      • 4.1.2 Game
      • 4.1.3 Playing the Game
      • 4.1.4 Next Iteration
    • 4.2 Our Refined Point-and-Click game
      • 4.2.1 GameScreen
      • 4.2.2 Game
      • 4.2.3 Further Development
  • 5 Ini File Editor
    • 5.1 Basic View and Edit Functionality
      • 5.1.1 init
      • 5.1.2 file_open
      • 5.1.3 parse_ini_file
      • 5.1.4 display_section_contents
      • 5.1.5 file_save
      • 5.1.6 Next Iteration
    • 5.2 Now With Caching and Resizing
      • 5.2.1 init and frame_height
      • 5.2.2 parse_ini_file
      • 5.2.3 display_section_contents
      • 5.2.4 file_save
      • 5.2.5 Running
      • 5.2.6 Next Iteration
    • 5.3 Our finished Ini Editor
      • 5.3.1 CentralForm
      • 5.3.2 AddSectionForm and AddItemForm
      • 5.3.3 IniEditor
      • 5.3.4 Further Development
  • 6 A Python Text Editor With Autocomplete and Syntax Highlighting
    • 6.1 Basic Functionality and Autocompletion
      • 6.1.1 init
      • 6.1.2 Handling Files
      • 6.1.3 Autocompletion
      • 6.1.4 Spaces over Tabs!?
      • 6.1.5 Next Iteration
    • 6.2 Syntax Highlighting
      • 6.2.1 init
      • 6.2.2 Regexes Explained
      • 6.2.3 file_open
      • 6.2.4 tag_keywords
      • 6.2.5 display_autocomplete_menu, number_of_leading_spaces, and on_key_release
      • 6.2.6 Next Iteration 4 CONTENTS
    • 6.3 Our Finished Editor
      • 6.3.1 FindPopup
      • 6.3.2 Editor
      • 6.3.3 The Finished Product
      • 6.3.4 Further Development
  • 7 A Pomodoro Timer
    • 7.1 A Basic Timer
      • 7.1.1 Timer
      • 7.1.2 CountingThread
      • 7.1.3 Next Iteration
    • 7.2 Keeping a Log
      • 7.2.1 Timer
      • 7.2.2 LogWindow
      • 7.2.3 Next Iteration
    • 7.3 Our Finished Timer
      • 7.3.1 Timer
      • 7.3.2 LogWindow
      • 7.3.3 Further Development
  • 8 Miscellaneous
    • 8.1 Alternate Geometry Managers
      • 8.1.1 Grid
      • 8.1.2 Place
    • 8.2 Tk Widgets
      • 8.2.1 Checkbutton
      • 8.2.2 Radiobutton
      • 8.2.3 Checkbuttons and Radiobuttons in a Menu
      • 8.2.4 OptionMenu
    • 8.3 Ttk Widgets
      • 8.3.1 Combobox
      • 8.3.2 Progressbar
    • 8.4 Final Words

0.1. INTRODUCTION 5

0.1 Introduction

Thank you for taking an interest in my book. Its purpose is to teach you everything you should need to know to begin using Tkinter in Python 3. Examples in this book cover Tkinter 8.6 in Python 3.6. If you wish to follow along using Python 2, there shouldn’t be too many differences, but keep in mind I haven’t tested the code for compatability. The main thing to note is that the module is likely called T k i n t e r (capital T), but in Python 3 it is t k i n t e r (small t).

Each chapter of this book is written in the form of an image of the target application with the app’s entire source code, followed by a breakdown and explanation of the code. Each example is included to teach a specific topic (or a bunch of related ones). Apps are developed iteratively, with each step adding a new feature and teaching a key part. Code which has not changed from the previous iteration will be condensed with ellipses (...) for brevity. I have also included some exercises at the end of each chapter for anyone who wishes to practice development by themselves.

0.2 Who this book is aimed at

This book is written for anyone who knows python and wants to learn a bit about developing GUI applications. Whether you’ve got a command line application you want to make friendlier with a GUI or you have a great idea for a GUI app which you want to get started on, this book will hopefully give you the tools you need to begin writing your own tkinter apps from scratch. I will assume that you have basic knowledge of python programming already, and will not explain things like installing python, running programs, or basic syntax (things like i f , f o r loops and such). At the same time, you will not need to be an expert to follow along either. I would suggest learning about C l a s s es if you aren’t already aware of them, as all of the examples are written using a class.

I hope you are able to learn something interesting from this book. Should you have any questions, feel free to contact me. I’m @Dvlv292 on Twitter and Dvlv on Reddit.

All source code from this book is freely available on my Github at http://github.com/Dvlv/Tkinter-By- Example.

0.3 How to get the most out of this book

The best way to ensure that the knowledge from any programming book really sticks in your mind is to write out the code for yourself. You can do this whilst reading the section or after finishing the explanation; it doesn’t really matter. The important thing is that you code along with the book. Reading the code can only get you so far - you need to practise, practise, practise!

Don’t just follow along either. If you wonder "what if I change this" or "couldn’t I do it like that?" then just do it! If you mess up, just start again, or grab the code from Github and "reset" back to where you were. You cannot go wrong.

0.4 About tkinter

0.4.1 Installing

Tkinter is probably already installed alongside python. Some Linux distros may not include it, so you might have to look for python3−t k i n t e r in your package manager. Check by running python in a terminal and trying to do >>> i m p o r t t k i n t e r.

Chapter 1

Hello World

1.1 Basic Example

As is tradition with all programming books, we’ll start with the classic Hello World example to introduce a few things. This will pop up a small window with "Hello World" written inside.

1 import tkinter as tk 2 3 root = tk.Tk() 4 5 label = tk.Label(root, text="Hello World", padx=10, pady=10) 6 label.pack() 7 8 root.mainloop()

Listing 1.1: Hello World

We start with root=tk.Tk() which creates the overall tk window. Then we define a tk.Label() which will hold our "Hello World" text. The first argument to a Tk widget is the parent in which it will be placed. In this case, we will just put it directly within the root instance. The padx and pady arguments add padding horizontally and vertically. label.pack() is then called as a way of placing the label into the root. Other ways of placing widgets, such as grid(), will be covered later. Finally root.mainloop() is responsible for showing the window.

Save and run this code and you should see a small window appear with "Hello World" inside, as show here:

Figure 1.1: Our first Tk window

8 CHAPTER 1. HELLO WORLD

1.2 Using Classes

Whilst Tkinter code can be written using only functions, it’s much better to use a class to keep track of all individual widgets which may need to reference each other. Without doing this, you need to rely on global or nonlocal variables, which gets ugly as your app grows. It also allows for much finer controls once your app gets more complex, allowing you to override default behaviours of Tkinter’s own objects. 1 import tkinter as tk 2 3 class Root(tk.Tk): 4 def init(self): 5 super().init() 6 7 self.label = tk.Label(self, text="Hello World", padx=5, pady=5) 8 9 self.label.pack() 10 11 if name == "main": 12 root = Root() 13 root.mainloop()

Listing 1.2: Hello World as a Class

The main code here is the same as above. The rest is simply creating a Root class inheriting from Tkin- ter’s Tk and running its mainloop function as before. I’ve also included the standard if "name" == main line for familiarity.

The label now belongs to the Root, rather than being an independent variable. This allows us to reference it easily within methods of the Root class, such as an action we may bind to a Button, which could otherwise be out of scope if we were not using a class.

Running this code should produce the same small window as in the first example.

Now we’ve covered the very basics of making a window appear, let’s dive in to something which can actually be used.

10 CHAPTER 2. A TO-DO LIST

Let’s get right into the code for the first iteration. 1 import tkinter as tk 2 3 class Todo(tk.Tk): 4 def init(self, tasks=None): 5 super().init() 6 7 if not tasks: 8 self.tasks = [] 9 else: 10 self.tasks = tasks 11 12 self.title("To-Do App v1") 13 self.geometry("300x400") 14 15 todo1 = tk.Label(self, text="--- Add Items Here ---", bg="lightgrey", fg="black", pady=10) 16 17 self.tasks.append(todo1) 18 19 for task in self.tasks: 20 task.pack(side=tk.TOP, fill=tk.X) 21 22 self.task_create = tk.Text(self, height=3, bg="white", fg="black") 23 24 self.task_create.pack(side=tk.BOTTOM, fill=tk.X) 25 self.task_create.focus_set() 26 27 self.bind("", self.add_task) 28 29 self.colour_schemes = [{"bg": "lightgrey", "fg": "black"}, {"bg": "grey", "fg": " white"}] 30 31 def add_task(self, event=None): 32 task_text = self.task_create.get(1.0,tk.END).strip() 33 34 if len(task_text) > 0: 35 new_task = tk.Label(self, text=task_text, pady=10) 36 37 _, task_style_choice = divmod(len(self.tasks), 2) 38 39 my_scheme_choice = self.colour_schemes[task_style_choice] 40 41 new_task.configure(bg=my_scheme_choice["bg"]) 42 new_task.configure(fg=my_scheme_choice["fg"]) 43 44 new_task.pack(side=tk.TOP, fill=tk.X) 45 46 self.tasks.append(new_task) 47 48 self.task_create.delete(1.0, tk.END) 49 50 if name == "main": 51 todo = Todo() 52 todo.mainloop()

Listing 2.1: Our Initial To-Do Framework

2.1.1 init

We start off by defining our Todo class and initialising it with an empty list of tasks. If using a mutable data-type, such as a list, always ensure you set the default argument to None and convert it into a list within the init method, as unexpected behaviour can occur if you try and pass an empty list in. The reasons why are beyond the scope of this book, but you can find great explanations and examples online.

2.1. A BASIC LIST APP 11

Next off, we set the title and size of the window. The app can be resized after creation if the user desires, so don’t worry too much about getting the initial size perfect. The main reason for this is to signal to the user that the app should be vertically-oriented and prefers to be taller rather than wider.

A default task is added to our list to prevent it from just being a big blank space with a text box at the bottom, and to hint to the user what will happen when a task is added. We do this by creating a Label, adding it to our tasks list and packing it. The reason we use a loop to pack this item will become clear when we introduce persistent storage in a later section of this chapter. The fg (foreground) and bg (background) colours are set, and some vertical padding is added for aesthetics. The widgets are packed to the TOP of the window, and are set to fill in the X direction, i.e. horizontally, to ensure they are all of uniform width, and the background spans the entirety of the window.

The final widget we need is our Text box, which is what the user will type into. We shorten the default height to 3 to make it look a bit nicer, and specify the white background with black text to look more like traditional text inputs. After packing it at the BOTTOM of our window spanning the full X direction like our tasks, we call focus_set so that the cursor is inside the box when the window is opened. Without this, the user would have to click inside the box before they could type anything. We then bind the Return (or Enter) key to a function add_item which we will get to next. A note when binding - do not put the parentheses at the end of the function name. We want to pass the function itself across, but if we put the parentheses we will end up calling the function instead.

The last thing to do is define our colour schemes. This is used to better separate individual items from the list view. I’ve gone for light grey with black text, followed by darker grey with white text. Feel free to switch these up to suit your preferences. You may notice the default list item has the styling of the first scheme, so as to ensure it fits the pattern. The colour_schemes variable is a list of dictionaries containing a background and foreground colour, which we will use to alternate the styles when adding new tasks.

2.1.2 add_item

When adding a new item, the first thing to do is get the text which the user entered into our Text widget. The arguments here tell the widget how much of the text to grab. 1.0 tells it to begin at the first character, and the END constant tells it to look until the end of the box. We also call strip() on the result to remove the newline character which is entered when the user presses Return to submit the text, as well as any trailing space characters.

We need to check if the length of the entered text is greater than 0 to avoid letting the user add blank tasks. If this is true, then we create a new Label with the text entered by the user. The divmod function is used to determine whether we are on an even or odd number of total tasks, allowing us to set the correct styling to our new label. Divmod returns the quotient and remainder when the first argument is divided by the second. In our case, we want the remainder when the size of our list is divided by 2. The quotient is set to _, which is commonly used in python to denote a variable which we do not plan on using. The remainder is then used as the index of our colour_schemes list to grab the correct foreground and background colour dictionary. The configure method is used to set a property of a widget, just as you would pass the values in as keyword arguments when creating them initially. We set the foreground and background colours of our Label with the chosen dictionary’s values, and then pack it the same way as our default item. Finally, we add this to the tasks variable so as to keep count of how many items we have.

We clear everything written in the Text widget outside of our if statement. This is to prevent the user from adding newlines before their task name by pressing Return before typing anything. We also want to clear it if they have entered a task, so they do not have to delete it manually before writing another.

2.2. SCROLLING AND DELETING 13

2.2 Scrolling and Deleting

A lot has changed from the previous iteration, so I will include the full code in this section. Your new To-do app can be written as follows: 1 import tkinter as tk 2 import tkinter.messagebox as msg 3 4 class Todo(tk.Tk): 5 def init(self, tasks=None): 6 super().init() 7 8 if not tasks: 9 self.tasks = [] 10 else: 11 self.tasks = tasks 12 13 self.tasks_canvas = tk.Canvas(self) 14 15 self.tasks_frame = tk.Frame(self.tasks_canvas) 16 self.text_frame = tk.Frame(self) 17 18 self.scrollbar = tk.Scrollbar(self.tasks_canvas, orient="vertical", command=self. tasks_canvas.yview) 19 20 self.tasks_canvas.configure(yscrollcommand=self.scrollbar.set) 21 22 self.title("To-Do App v2") 23 self.geometry("300x400") 24 25 self.task_create = tk.Text(self.text_frame, height=3, bg="white", fg="black") 26 27 self.tasks_canvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 28 self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y) 29 30 self.canvas_frame = self.tasks_canvas.create_window((0, 0), window=self. tasks_frame, anchor="n") 31 32 self.task_create.pack(side=tk.BOTTOM, fill=tk.X) 33 self.text_frame.pack(side=tk.BOTTOM, fill=tk.X) 34 self.task_create.focus_set() 35 36 todo1 = tk.Label(self.tasks_frame, text="--- Add Items Here ---", bg="lightgrey", fg="black", pady=10) 37 todo1.bind("", self.remove_task) 38 39 self.tasks.append(todo1) 40 41 for task in self.tasks: 42 task.pack(side=tk.TOP, fill=tk.X) 43 44 self.bind("", self.add_task) 45 self.bind("", self.on_frame_configure) 46 self.bind_all("", self.mouse_scroll) 47 self.bind_all("", self.mouse_scroll) 48 self.bind_all("", self.mouse_scroll) 49 self.tasks_canvas.bind("", self.task_width) 50 51 self.colour_schemes = [{"bg": "lightgrey", "fg": "black"}, {"bg": "grey", "fg": " white"}] 52 53 def add_task(self, event=None): 54 task_text = self.task_create.get(1.0,tk.END).strip() 55 56 if len(task_text) > 0: 57 new_task = tk.Label(self.tasks_frame, text=task_text, pady=10)

14 CHAPTER 2. A TO-DO LIST

58 59 self.set_task_colour(len(self.tasks), new_task) 60 61 new_task.bind("", self.remove_task) 62 new_task.pack(side=tk.TOP, fill=tk.X) 63 64 self.tasks.append(new_task) 65 66 self.task_create.delete(1.0, tk.END) 67 68 def remove_task(self, event): 69 task = event.widget 70 if msg.askyesno("Really Delete?", "Delete " + task.cget("text") + "?"): 71 self.tasks.remove(event.widget) 72 event.widget.destroy() 73 self.recolour_tasks() 74 75 def recolour_tasks(self): 76 for index, task in enumerate(self.tasks): 77 self.set_task_colour(index, task) 78 79 def set_task_colour(self, position, task): 80 _, task_style_choice = divmod(position, 2) 81 82 my_scheme_choice = self.colour_schemes[task_style_choice] 83 84 task.configure(bg=my_scheme_choice["bg"]) 85 task.configure(fg=my_scheme_choice["fg"]) 86 87 def on_frame_configure(self, event=None): 88 self.tasks_canvas.configure(scrollregion=self.tasks_canvas.bbox("all")) 89 90 def task_width(self, event): 91 canvas_width = event.width 92 self.tasks_canvas.itemconfig(self.canvas_frame, width = canvas_width) 93 94 def mouse_scroll(self, event): 95 if event.delta: 96 self.tasks_canvas.yview_scroll(int(-1*(event.delta/120)), "units") 97 else: 98 if event.num == 5: 99 move = 1 100 else: 101 move = - 102 103 self.tasks_canvas.yview_scroll(move, "units") 104 105 if name == "main": 106 todo = Todo() 107 todo.mainloop()

Listing 2.2: Our Scrolling To-Do

16 CHAPTER 2. A TO-DO LIST

2.2.5 Mouse scrolling

Our final method, mouse_scroll, is how we bind scrolling to the mouse wheel as well as the scrollbar. This is bound to for Windows and OSX, and to and for Linux. We then simply call the Canvas’ yview_scroll method based upon whether we receive a delta or a num within the event. Here on Linux I get a num. The delta is usually 120 or -120, so is divided by 120 for more precise scrolling, and multiplied by -1 to adjust the direction.

2.2.6 Next Iteration

Our final iteration will handle saving and retrieving values from a sqlite database. I have left this until last because it’s not strictly tkinter related, and so you are free to skip this section if you have no interest in learning about databases, or you already know enough to figure out how to do this on your own. If you think the latter is true, please do go ahead and try as an exercise before reading this section.

2.3. PERMANENT STORAGE 17

2.3 Permanent Storage

There are only a few small changes to our existing methods in this iteration, so I will not re-print the whole class. If you wish to follow along, start with your code from the previous version, make the changes listed in this section, and add any other new methods to the end of our Todo class. As a reminder, the full code will be available on Github at http://github.com/Dvlv/Tkinter-By-Example as Chapter2-3.py. 1 import tkinter as tk 2 import tkinter.messagebox as msg 3 import os 4 import sqlite 5 6 class Todo(tk.Tk): 7 def init(self, tasks=None): 8 ... 9 10 self.title("To-Do App v3") 11 12 ... 13 14 self.colour_schemes = [{"bg": "lightgrey", "fg": "black"}, {"bg": "grey", "fg": " white"}] 15 16 current_tasks = self.load_tasks() 17 for task in current_tasks: 18 task_text = task[0] 19 self.add_task(None, task_text, True) 20 21 ... 22 23 def add_task(self, event=None, task_text=None, from_db=False): 24 if not task_text: 25 task_text = self.task_create.get(1.0,tk.END).strip() 26 27 if len(task_text) > 0: 28 new_task = tk.Label(self.tasks_frame, text=task_text, pady=10) 29 30 self.set_task_colour(len(self.tasks), new_task) 31 32 new_task.bind("", self.remove_task) 33 new_task.pack(side=tk.TOP, fill=tk.X) 34 35 self.tasks.append(new_task) 36 37 if not from_db: 38 self.save_task(task_text) 39 40 self.task_create.delete(1.0, tk.END) 41 42 def remove_task(self, event): 43 task = event.widget 44 if msg.askyesno("Really Delete?", "Delete " + task.cget("text") + "?"): 45 self.tasks.remove(event.widget) 46 47 delete_task_query = "DELETE FROM tasks WHERE task=?" 48 delete_task_data = (task.cget("text"),) 49 self.runQuery(delete_task_query, delete_task_data) 50 51 event.widget.destroy() 52 53 self.recolour_tasks() 54 55 ... 56 57 def save_task(self, task): 58 insert_task_query = "INSERT INTO tasks VALUES (?)"

2.3. PERMANENT STORAGE 19

2.3.1 runQuery

Let’s start by explaining the database handling. Our runQuery method is a fairy generic database handling method. It takes an sql string, some data to format into the sql string, and receive which indicates to the method whether or not it needs to return any data (from a SELECT statement). We first connect to our database file, in this case tasks.db, and receive a cursor. The cursor is used to execute queries against the database and sometimes return data. We then close off our connection at the end to reduce resource usage. This is a static method so that it can be called by our proceeding firstTimeDb method, which needs to be called before our init, and so is also static.

2.3.2 firstTimeDb

This function is used to create the database file, tasks.db, if it does not already exist. We also put our old default task, --- Add Tasks Here ---, in this method so that it appears when the user first loads the app, but is permanently deletable like other tasks.

2.3.3 init

We start by just updating the window’s title bar to the 3rd version. We move the existing colour_schemes variable to above the new code which will populate our existing tasks, so that we can use it during the initial set-up. Without doing this, we would get an error when we reference it via add_task. Instead of the hard-coded default task, we now fetch existing tasks from the database with load_tasks, then iterate through them, passing each to our slightly altered add_task method.

2.3.4 add_task and remove_task

To prevent re-writing most of this code in our init method, we have added two new parameters to add_task: task_text and from_db. This allows us to pass in text independent of our Text widget, and to prevent re-saving tasks to the database which originated from there. Before destroying our widget inside remove_task, we grab its text and remove it from the database too.

2.3.5 save_task and load_tasks

These two methods deal with database access. save_task will add a new task into our database, and load_tasks is called in our init method to retrieve all saved tasks when loading the app. These two methods ensure that the task list displays the same when the user closes then re-opens the app.

2.3.6 The final app

That’s it for our to-do list. We now have a to-do application which can save and retrieve tasks which remain after closing the app. We have learned how to layout multiple widgets with Frames and the pack method, how to make a scrollable area which maintains its size when the window is resized, how to bind methods to user inputs and tkinter’s own events, and how to dynamically add and remove widgets based on user actions. If you read the final section, you will also know how to integrate tkinter nicely with a sqlite database. Next up we will create an app which utilises a tabbed interface, also known as a Notebook.

2.3.7 Further Development

If you’d like to continue work on this project as an exercise, try the following:

  • Prevent duplicate tasks by using a database look-up before adding a new task.
  • Give each task a "Delete" button instead of the on-click event on the Label itself (Buttons will be covered next chapter).
  • Instead of destroying tasks, mark them as "finished" using a column in the database and display them as "greyed out".

20 CHAPTER 2. A TO-DO LIST

  • Add a "category" for each task and colour the task based on the category instead of using the pattern (maybe separate them with a border).