Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
Search icon CANCEL
Subscription
0
Cart icon
Your Cart(0 item)
Close icon
You have no products in your basket yet
Save more on your purchases!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Programming> GUI Application Development> Tkinter GUI Programming by Example
Tkinter GUI Programming by Example
Tkinter GUI Programming by Example

Tkinter GUI Programming by Example: Learn to create modern GUIs using Tkinter by building real-world projects in Python

Arrow left icon
Profile Icon David Love
Arrow right icon
₹4096.99
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1(3 Ratings)
PaperbackApr 2018340 pages1st Edition
eBook
₹799.99 ₹3276.99
Paperback
₹4096.99
Subscription
Free Trial
Renews at ₹800p/m
eBook
₹799.99 ₹3276.99
Paperback
₹4096.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with Print?

Product feature iconInstant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Shipping Address

Billing Address

Shipping Methods
Table of content iconView table of contentsPreview book icon Preview Book

Tkinter GUI Programming by Example

Meet Tkinter

Hello, and welcome toTkinter GUI Programming by Example. In this book, we will be building three real-world desktop applications using Python and Tkinter. You will gain the knowledge to fully utilize Tkinter's vast array of widgets to create and lay out any application you choose.

So why use Tkinter? Tkinter comes bundled with Python most of the time, meaning there's no arduous installation process. It's also licensed under a free software license, meaning, unlike some other GUI frameworks, there's no complicated licensing model to battle against when you want to release your software to the outside world.

Tkinter is also very quick and easy to learn. Code can be written both procedurally or using object-oriented practices (which is the preferred style for anything non-experimental), and runs perfectly on any operating system supporting Python development, including Windows, macOS, and Linux.

In this first chapter, we will cover the following topics:

  • Ensuring Tkinter is installed and available
  • Creating a main window in which to display your application
  • Laying out widgets inside the window via geometry managers
  • Creating widgets and displaying them inside your main window
  • Displaying static information via alabel widget
  • Creating interactivity with theButton widget
  • Tying widgets to Python functions
  • Using Tkinter's special variables
  • Displaying pop-up messages easily
  • Getting information from the user

Installation

Most of the time, you will not need to install Tkinter as long as you have Python installed. To check, open an instance of the interactive interpreter and typeimport tkinter (Python 3) orimport Tkinter (Python 2). If you don't see an error, then Tkinter is already installed and you are ready to go! Some flavors of Linux will not come with Tkinter by default, and if you receive an error message while performing the previous step, search your distribution's package manager. On Debian-based distributions such as Ubuntu, the package should be calledpython3-tk. On RPM-based distributions, including Fedora, you may instead find a package calledpython3-tkinter.

Examples in this book will be written using Python 3.6.1 and Tkinter 8.6. I recommend you also use these versions, or as close to them as possible, when following along. To check your Tkinter version, open an interactive Python prompt and type the following:

>>> import tkinter
>>> tkinter.TkVersion

Once you've got Tkinter installed and ready, we can move on to a brief overview of how we will be structuring a Tkinter application and then dive in and write our first program.

How will the code be structured?

Tkinter exposes many classes. These are known as widgets. A widget is typically any part of the application that needs to be drawn onto the screen, including the main window.

A Tkinter application always needs to have a main window. This is what will be drawn on the screen for the user to see. This is crucial for any GUI application, so much so that if you do not define one, Tkinter will try to create one for you (though you should never rely on this!). The widget that performs this job is calledTk.

TheTk widget exposes various window properties, such as the text within the top bar of the application, the size of the application, its position on screen, whether it can be resized, and even the icon which appears in the top right-hand corner (on Windows only).

Because of this feature exposure, it is very common for the main class of an application to inherit from theTk widget, though any Tkinter widget can be subclassed to add program-specific functionality.

There is no set convention for what the subclass should be called. Some like to call itRoot, some chooseApp, and others (such as myself) prefer to name it after the program itself. For example, a shopping list program would have a class calledShoppingList that inherits fromTk. Bear this in mind when looking through other sources of information on Tkinter.

Once you have a main window defined, you can begin adding other widgets into it. All other widgets must belong to a parent which has the ability to display them, such as aTk orFrame. Each widget is only visible if its parent is. This allows us to group widgets into different screens and show or hide groups of them as need be.

Widgets are placed into their parents using special functions calledgeometry managers. There are three geometry managers available in Tkinter –pack,grid, andplace. Let's take a look at each of them in detail.

Geometry managers

Geometry managers serve the purpose of deciding where in the parent widget to render its children. Each of the three geometry managers uses a different strategy and therefore takes different arguments. Let's go over each one in detail, looking at how it decides the positions of new widgets and what sort of arguments need to be provided.

pack

Thepack geometry manager acts based on the concept of using up free space within the parent widget. When packing, you can specify at which end of the free space to put the widget, and how it will grow along with said free space (as the window itself grows and shrinks). The geometry manager than assigns widgets into said free space, leaving as little empty space as possible.

Thepack geometry manager is primarily controlled by three keyword arguments:

  • side: On which end of the available space do you want to place the widget? The options are defined as constants within Tkinter, asLEFT,RIGHT,TOP, and BOTTOM.
  • fill: Do you want the widget to fill any available space around it? The options are also constants:X orY. These are Cartesian, meaningX is horizontal andY is vertical. If you want the widget to expand in both directions, use theBOTH constant.
  • expand: Should the widget resize when the window does? This argument is a Boolean, so you can passTrue or1 to make the widget grow with the window.

These are not the only arguments that can be provided topack; there are others which handle things such as spacing, but these are the main ones you will use. Thepackgeometry manager is somewhat difficult to explain, but tends to create very readable code thanks to its use of words to describe positions.

The order in which widgets are packed matters greatly. Suppose you have two buttons which you wish to stack vertically, with one underneath the other. The first button, which you callpack(side=tk.BOTTOM) on, will be at the very bottom of the main window. The next widget, which is packed withside=tk.BOTTOM, will then appear above it. Bear this in mind if your widgets appear to be out of order when usingpack as your geometry manager.

grid

Thegrid—as the name suggests—treats the parent widget as agrid containing rows and columns of cells. If you are familiar with spreadsheet software,grid will work in the same way. Thegrid lines will not be visible, they are just conceptual.

To specify the position within thegrid, therow andcolumn keywords are used. These accept integer values and begin at0, not1. A widget placed withgrid(row=0, column=0) will be to the left of a widget atgrid(row=0, column=1). Underneath these would sit a widget placed atgrid(row=1, column=0).

To make a widget span more than one cell, usecolumnspan for a horizontal size increase androwspan for a vertical increase. So, to make our hypothetical bottom widget sit below both, the full argument set would begrid(row=1, column=0, columnspan=2).

By default, a widget will sit in the center of its assigned cell(s). In order to make the widget touch the very edge of its cell, we can use thesticky argument. This argument takes any number of four constants:N,S,E, andW. These are abbreviations for North, South, East, and West. Passing inW orE will align the widget to the left or right, respectively.S andN will align to the bottom and top.

These constants can be combined as desired, soNE will align top right andSW will sit the widget bottom left.

If you wish for the widget to span the entire vertical space, useNS. Similarly, useEW to stretch to the full size in the horizontal direction.

If you instead want the widget to fill the whole cell edge to edge,NSEW will let you do this.

Thepack andgrid are both intended to lay out the entire content of a parent widget and apply different logic to decide where each new widget added should go. For this reason, they cannot be combined inside the same parent. Once one widget is inserted usingpack orgrid, all other widgets must use the same geometry manager. You can, however,pack widgets into oneFrame,grid widgets into another, thenpack/grid both of thoseFrame widgets into the same parent. 

place

Unlikepack andgrid, which automatically calculate where each new widget is added,place can be used in order to specify an exact location for a particular widget.place takes eitherx andy coordinates (in pixels) to specify an exact spot, which will not change as the window is resized, or relative arguments to its parent, allowing the widget to move with the size of the window.

To place a widget at (5, 10) within the window, you would writewidget.place(x=5, y=10).

To keep a widget in the direct center, you would usewidget.place(relx=0.5, rely=0.5).

place also takes sizing options, so to keep a widget at 50 percent width and 25 percent height of the window, add(relwidth=0.5, relheight=0.25).

place is rarely used in bigger applications due to its lack of flexibility. It can be tiresome keeping track of exact coordinates for a widget, and as things change with the application, widgets may resize, causing unintended overlapping.

For a smaller window with only one or two widgets – say a custom pop-up message –place could be a viable choice of geometry manager, since it allows for very easy centering of said widgets.

One thing to note is thatplace can be used alongsidepack orgrid within the same parent widget. This means that if you have just one widget which you need to put in a certain location, you can do so quickly without having to restructure your already packed or gridded widgets.

To pack or to grid?

Usingpack versusgrid in your application is mostly down to personal preference. There doesn't seem to be a particularly dominant reason to use one over the other.

The main advantage ofpack is the code tends to be very readable.pack uses words such as left andtop to make it clear where the programmer wants the widget to go.

When usingpack, sections of the window are also split using frames to allow for much greater control. When variables are named sensibly, this allows anyone changing the code to know exactly which part of a window the widget will end up in (by its parentFrame) and prevents them from having unexpected consequences when changing widgets, such as resizing a widget in the top-left corner of an application, knocking a widget at the bottom out of alignment.

Thegrid can also take advantage ofFrame widgets too, but this can sometimes cause alignment issues.

Finally,pack works out widget positions based mainly on the argument and the order in which they are added. This means that when a new widget is added among existing ones, it is usually quite easy to get it into the correct spot. Simply adjust the order in which yourwidget.pack() calls occur. When usinggrid, you may need to change quite a few row and column arguments in order to slot the widget where you need it and keep everything else in their correct positions.

The great advantage ofgrid is its code simplicity to layout complexity ratio. Without the need to split your application into frames, you can save many lines of code and lay out a complicated window design with essentially just one line of code per widget.

You also don't need to worry about the order in which you add your widgets to their parent as the numericalgrid system will apply regardless.

In the end, both prove to be good tools for the job and there is no need to use one if you prefer the other.

My personal preference is to usepack for main windows which may change quite a bit during development, and sometimesgrid for smaller windows or layouts which are written in one go. Any additional windows for an application which would require more than twoFrame widget are often better off being managed bygrid for simplicity's sake.

Examples in this book will cover bothgrid andpack, so you will be able to practice both and decide which you prefer.

Getting going

Now that we have the basic understanding of the concept of widgets and how to add them into a window, it's time to put this into practice and make ourselves an application!

As with almost all programming examples, we will start with aHello World application. Don't feel cheated though, it will have interactive aspects too! Let's begin with the most important step for any GUI application—showing a window. Start by opening your choice of text editor or IDE and putting in the following code:

import tkinter as tk

class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Tkinter")

label = tk.Label(self, text="Hello World!")
label.pack(fill=tk.BOTH, expand=1, padx=100, pady=50)


if __name__ == "__main__":
window = Window()
window.mainloop()

Let's break this first step down. We begin by importing Tkinter and giving it the alias oftk for brevity. Every example in this book should include this line so that we have access to all of Tkinter's widgets, including the main window.

Speaking of widgets, we begin this example by subclassing Tkinter's main window widget—Tk. Doing so allows us to change various aspects of it, including the title which will display inside the window's top bar. We set the title toHello Tkinter in this example.

Next, we want to display some text within our window. To do this, we use aLabel widget. ALabel widget is typically non-interactive and is used to display either text or an image.

When defining Tkinter widgets, the first argument is always the parent (sometimes called master) which will hold the widget. We useself to refer to our main window in this case. Afterward, we have a vast array of keyword arguments to use in order to change their properties. The text argument here will take a string which tells the label what to display. Our label will sayHello World!

Now that we have two widgets, we need to place the label inside of our main window (Tk) so that they both display. To do this with Tkinter, we utilize one of the geometry managers we covered earlier. For our first example, we will be usingpack. Pack has been given the following arguments:

  • fill: This tells the widget to take all the space in both directions

  • expand: This tells the widget to expand when the window is resized

  • padx: Padding (empty space) of 100 pixels in thex direction (left, right)

  • pady: Padding of 50 pixels in they direction (above, below)

With that, ourHello World is ready to run. In order to tell the main window to show itself, we call themainloop method. This is all enclosed within the (hopefully familiar)if __name__ == "__main__" block. Utilizing this block allows widgets from one file to be imported into another file for reuse without creating multiple main windows.

Execute the code via your preferred method and you should see a little window appear. Congratulations! You have now written your first GUI application with Tkinter!:

Our Hello World application

Adding interactivity

Of course, without any interactivity, this is just a message box. Let's add something for the user to do with our application. Bring the source code back up and change the__init__ method to look like this:

class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Tkinter")

self.label = tk.Label(self, text="Choose One")
self.label.pack(fill=tk.BOTH, expand=1, padx=100, pady=30)

hello_button = tk.Button(self, text="Say Hello",
command=self.say_hello)
hello_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20))

goodbye_button = tk.Button(self, text="Say Goodbye",
command=self.say_goodbye)
goodbye_button.pack(side=tk.RIGHT, padx=(0, 20), pady=(0, 20))

Our label has changed to sayChoose one to indicate that the user can now interact with the application by selecting one of the two buttons to click. A button in Tkinter is created by adding an instance of theButton widget.

TheButton widget is exactly what you would imagine; something the user can click on to execute a certain piece of code. The text displayed on aButton is set via thetext attribute, much like with aLabel, and the code to run when clicked is passed via thecommand argument.

Be sure to remember that the argument passed to command must be a function, and should not be called (by adding parentheses). This means your code willnot behave as intended if you usecommand=func() instead ofcommand=func.

Our two buttons are placed within our main window usingpack. This time, we use theside keyword argument. This tells the geometry manager where to place the item inside the window. Ourhello_button will go on the left, and ourgoodbye_button will go on the right.

We also usepadx andpady to give some spacing around the buttons. When a single value is given to these arguments, that amount of space will go on both sides. When a tuple is passed instead, the format is (above, below) forpady and (left, right) forpadx. You will see in our example that both buttons have 20 pixels of padding below them; our leftmost button has 20 pixels of padding to its left, and our rightmost has 20 pixels to its right. This serves to keep the buttons from touching the edge of the window.

We now need to define the functions which will run when each button is pressed. OurSay Hello button callssay_hello and ourSay Goodbye button callssay_goodbye. These are both methods of ourWindow class and so are prefixed withself. Let's write the code for these two methods now:

def say_hello(self):
self.label.configure(text="Hello World!")

def say_goodbye(self):
self.label.configure(text="Goodbye! \n (Closing in 2 seconds)")
self.after(2000, self.destroy)

Insay_hello, we will update the text of our label widget toHello World! as it was before. We can change attributes of Tkinter widgets using theconfigure method. This then takes a keyword argument and value, just like when we created them initially.

Oursay_goodbye method will also update the label's text and then close the window after two seconds. We achieve this using theafter method from ourTk widget (which we have subclassed intoWindow). This method will call a piece of code after a certain amount of time has elapsed (in milliseconds).

Thedestroy method can be called on any Tkinter widget, and will remove it from the application. Destroying the main window will cause your application to exit, so use it carefully.

Leave theif __name__ == "__main__" block as it was before and give this application a try. You should see now that both buttons will do something. It may not look like many lines of code, but we have now covered quite a lot of the things a GUI application will need to do. You may be getting the following output:

Our application now with two buttons

We have provided user interactivity withButton widgets and seen how to link a button press to a piece of code. We've also covered updating elements of the user interface by changing the text displayed in ourLabel widget. Performing actions outside of the main loop has also happened when we used theafter method to close the window. This is an important aspect of GUI development, so we will revisit this later.

Using variables

Instead of usingconfigure to repeatedly change the text within our label, wouldn't it be better if we could assign a variable to it and just change this variable? The good news is you can! The bad news? Regular Python variables aren't perfectly compatible with Tkinter widgets. Shall we take a look?

Our first try

Let's give it a try the regular way. Open up your previous code and change it to look like this:

class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Tkinter")
self.label_text = "Choose One"

self.label = tk.Label(self, text=self.label_text)
self.label.pack(fill=tk.BOTH, expand=1, padx=100, pady=30)

hello_button = tk.Button(self, text="Say Hello",
command=self.say_hello)
hello_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20))

goodbye_button = tk.Button(self, text="Say Goodbye",
command=self.say_goodbye)
goodbye_button.pack(side=tk.RIGHT, padx=(0, 20), pady=(0, 20))

def say_hello(self):
self.label_text = "Hello World"

def say_goodbye(self):
self.label_text="Goodbye! \n (Closing in 2 seconds)"
self.after(2000, self.destroy)


if __name__ == "__main__":
window = Window()
window.mainloop()

Give this code a whirl and click on yourSay Hello button. Nothing happens. Now try yourSay Goodbye button. The label will not update, but the window will still close after 2 seconds. This goes to show that the code written is not invalid, but will not behave as we may expect it to.

Creating Tkinter-compatible variables

So, how would we go about using a variable to update this label? Tkinter comes with four built-in variable objects for us to handle different data types:

  • StringVar: This holds characters like a Python string.
  • IntVar: This holds an integer value.
  • DoubleVar: This holds a double value (a number with a decimal place).
  • BooleanVar: This holds a Boolean to act like a flag.

To create a variable, just instantiate it like any other class. These do not require any arguments. For example:

label_text = tk.StringVar()

Using and updating

Since these variables are objects, we cannot assign to them a statement likelabel_text = "Hello World!". Instead, each variable exposes aget andset method. Let's have a play with these in the interactive shell:

>>> from tkinter import *
>>> win = Tk()
>>> sv = StringVar()
>>> sv
<tkinter.StringVar object at 0x05F82D50>
>>> sv.get()
''
>>> sv.set("Hello World!")
>>> sv.get()
'Hello World!'
>>> sv.set(sv.get() + " How's it going?")
>>> sv.get()
"Hello World! How's it going?"

These variables are passed to widgets inside their keyword arguments upon creation (or at a later stage, usingconfigure). The keyword arguments expecting these special variables will usually end invar.  In the case of a label, the argument istextvar.

Fixing our application

Let's get ourHello World application working as intended again using our new knowledge of Tkinter variables. After setting the title, change thelabel_text property as follows:

self.label_text = tk.StringVar()
self.label_text.set("Choose One")

Now, alter our other two methods like so:

def say_hello(self):
self.label_text.set("Hello World")

def say_goodbye(self):
self.label_text.set("Goodbye! \n (Closing in 2 seconds)")
self.after(2000, self.destroy)

Once again, run the application and click both buttons. Everything should now be all working as before.

Great! We now know how to take advantage of Tkinter's special variables, and it's super easy.

Showing messages

Often, a GUI application will need to tell the user something. Using what we have learned at the moment, we could make severalLabel widgets which update depending on the results of some other functions. This would get tedious and take up a lot of space within the application's window.

A much better way to achieve this is to use a pop-up window. These can be created manually, but Tkinter also comes with a few pre-built pop-ups which are already laid out and ready to display any message the programmer passes to them.

Let's adjust ourHello World application to utilize these windows to display the chosen message to the user.

Import themessagebox module with the following statement:

import tkinter.messagebox as msgbox

Now update the non-init methods to utilize this module:

def say_hello(self):
msgbox.showinfo("Hello", "Hello World!")

def say_goodbye(self):
self.label_text.set("Window will close in 2 seconds")
msgbox.showinfo("Goodbye!", "Goodbye, it's been fun!")
self.after(2000, self.destroy)

Run this version of our application and try out both buttons.

Showing information with showinfo

You should be able to see what the two arguments toshowinfo do.

The first argument is the window's title bar text. If you didn't notice, click theSay Hello button again – you should see the wordHello inside the title bar of the pop-up window.

Clicking theSay Goodbye button will yield a pop-up message withGoodbye! in the title bar.

The second argument is a string containing the information which will be written inside the box.

Theshowinfo box contains just one button—anOK button. Clicking this button dismisses the window:

A showinfo box

While amessagebox window is displayed, the main window is effectively paused. TheSay Goodbye button demonstrates this well. The line which tells the main window to close after 2 seconds does not get executed until themessagebox is dismissed.

Try clicking theSay Goodbye button and waiting for more than 2 seconds. You will see that the main window stays open until 2 seconds after you click OK to close themessagebox window. This is important to remember.

If, for example, you are processing a large list of items and you wish to alert the user to their status, it's best to wait until all of the items are processed before usingshowinfo. If you put ashowinfo box after each item, the user will have to continually close them in order to allow the main window to continue processing.

Showing warnings or errors

If the information to convey is more serious, you can let the user know withshowwarning.

If something goes wrong, tell the user withshowerror instead.

Both of these function the same as theshowinfo box that we have practiced but display a different image inside the box.

Try changing theshowinfo insay_hello to ashowwarning and theshowinfo insay_goodbye to ashowerror to see what these boxes will look like.

Getting feedback from the user

Should you require something back from the user, Tkinter has four more message boxes for you:

  • askquestion
  • askyesno
  • askokcancel
  • askretrycancel

askquestion will allow any question to be passed in and providesYes andNo answers. These are returned to the program as the string literals"yes" and"no".

askyesno does the same, but will return 1 onYes and nothing onNo.

askokcancel providesOK andCancel buttons to the user.OK returns1 andCancel nothing.

askretrycancel providesRetry andCancel buttons.Retry returns1 andCancel nothing.

Despite the seemingly large number of choices, these all do pretty much the same thing. There doesn't seem to be much of a use case foraskquestion overaskyesno since they provide the same button choices, butaskquestion will produce cleaner code thanks to the return values.

Let's seeaskyesno in action within ourHello World application.

Change thesay_goodbye method to the following:

def say_goodbye(self):
if msgbox.askyesno("Close Window?", "Would you like to
close this window?"):
self.label_text.set("Window will close in 2 seconds")
self.after(2000, self.destroy)
else:
msgbox.showinfo("Not Closing", "Great! This window
will stay open.")

Run this application and try clicking theSay Goodbye button. You will now be asked whether you want to close the window. Give bothNo andYes a try:

Our askyesno box

From the code for this function, you should see that theaskyesno method can be treated like a Boolean statement. If you don't like doing this in one go, you could always use a variable such as the following:

close = msgbox.askyesno("Close Window?", "Would you like to close this window?")
if close:
self.close()

Getting text input

We now know how to get Boolean information from our user, but what if we want to get something more detailed, such as text?

Tkinter provides us with the perfect widget to do just this –Entry.

AnEntry widget is a one-line text entry box which is put into a parent widget just like aLabel orButton. The special Tkinter variables can be attached to anEntry to make getting the value out a breeze.

Why don't we add some personalization to ourHello World application? Grab your code and adjust it to the following:

class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Tkinter")
self.label_text = tk.StringVar()
self.label_text.set("My Name Is: ")

self.name_text = tk.StringVar()

self.label = tk.Label(self, textvar=self.label_text)
self.label.pack(fill=tk.BOTH, expand=1, padx=100, pady=10)

self.name_entry = tk.Entry(self, textvar=self.name_text)
self.name_entry.pack(fill=tk.BOTH, expand=1, padx=20, pady=20)

hello_button = tk.Button(self, text="Say Hello",
command=self.say_hello)
hello_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20))

goodbye_button = tk.Button(self, text="Say Goodbye",
command=self.say_goodbye)
goodbye_button.pack(side=tk.RIGHT, padx=(0, 20), pady=(0, 20))

If you run this version of the code, you will now see a text box in which to enter your name. As we enter our name in theEntry widget, its value is automatically assigned to thename_text StringVar thanks to thetextvar keyword argument:

Our application now with an Entry widget

The buttons will still function the same, however, so let's do something about that:

def say_hello(self):
message = "Hello there " + self.name_entry.get()
msgbox.showinfo("Hello", message)

def say_goodbye(self):
if msgbox.askyesno("Close Window?", "Would you like to
close this window?"):
message = "Window will close in 2 seconds - goodybye " + self.name_text.get()
self.label_text.set(message)
self.after(2000, self.destroy)
else:
msgbox.showinfo("Not Closing", "Great! This window
will stay open.")

These functions demonstrate both of the ways we can now grab the value back out of ourEntry widget. We can either call theget method of theEntry itself, or grab the value out of ourStringVar (also with theget method).

If theEntry box itself is the only part of your application which will need to use its value, I would recommend just grabbing it directly via.get() and foregoing the use of aStringVar. If, however, its value will be needed by other parts of your application, using aStringVar is probably the best way. This allows you to use theset method to adjust its value programmatically.

Summary

With this, ourHello World application has taught us all we should need to know with regard to basic GUI functionality. We have learned how to spawn a window containing various GUI elements by utilizing Tkinter's built-in widgets. We can place these widgets into the window using special functions called geometry managers, of which we have three to choose from.

Themessagebox module allows us to easily convey information to the user without having to use any widgets within our main window, and can also be used to get feedback from a user and control how our window will behave.

We've added three simple, but effective widgets to our arsenal (not including the main window): theLabel, for displaying static information; theButton, which allows a user to execute functions by clicking on it; and theEntry, which gathers textual information and allows for its use by our applications.

Next on our agenda is something a little different—a game of blackjack! By writing this game, we will also cover a very common starting point among programmers interested in GUI development: having a command-line application which could be improved by becoming a graphical one. In order to do this, we will briefly step back to the world of the CLI. 

Download code iconDownload Code

Key benefits

  • The fundamentals of Python and GUI programming with Tkinter.
  • Create multiple cross-platform projects by integrating a host of third-party libraries and tools.
  • Build beautiful and highly-interactive user interfaces that target multiple devices.

Description

Tkinter is a modular, cross-platform application development toolkit for Python. When developing GUI-rich applications, the most important choices are which programming language(s) and which GUI framework to use. Python and Tkinter prove to be a great combination. This book will get you familiar with Tkinter by having you create fun and interactive projects. These projects have varying degrees of complexity. We'll start with a simple project, where you'll learn the fundamentals of GUI programming and the basics of working with a Tkinter application. After getting the basics right, we'll move on to creating a project of slightly increased complexity, such as a highly customizable Python editor. In the next project, we'll crank up the complexity level to create an instant messaging app. Toward the end, we'll discuss various ways of packaging our applications so that they can be shared and installed on other machines without the user having to learn how to install and run Python programs.

Who is this book for?

This book is for beginners to GUI programming who haven’t used Tkinter yet and are eager to start building great-looking and user-friendly GUIs. Prior knowledge of Python programming is expected.

What you will learn

  • * Create a scrollable frame via theCanvas widget
  • * Use the pack geometry manager andFrame widget to control layout
  • * Learn to choose a data structurefor a game
  • * Group Tkinter widgets, such asbuttons, canvases, and labels
  • * Create a highly customizablePython editor
  • * Design and lay out a chat window
Estimated delivery feeDeliver to India

Premium delivery5 - 8 business days

₹630.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date :Apr 25, 2018
Length:340 pages
Edition :1st
Language :English
ISBN-13 :9781788627481
Category :
Languages :
Tools :

What do you get with Print?

Product feature iconInstant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Shipping Address

Billing Address

Shipping Methods
Estimated delivery feeDeliver to India

Premium delivery5 - 8 business days

₹630.95
(Includes tracking information)

Product Details

Publication date :Apr 25, 2018
Length:340 pages
Edition :1st
Language :English
ISBN-13 :9781788627481
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
₹4500billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick iconExclusive print discounts
₹5000billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick iconExclusive print discounts

Frequently bought together


Tkinter GUI Application Development Blueprints, Second Edition
Tkinter GUI Application Development Blueprints, Second Edition
Read more
Mar 2018422 pages
Full star icon4 (5)
eBook
eBook
₹799.99₹3276.99
₹4096.99
Tkinter GUI Application Development Cookbook
Tkinter GUI Application Development Cookbook
Read more
Mar 2018242 pages
Full star icon4.4 (7)
eBook
eBook
₹799.99₹2621.99
₹3276.99
Tkinter GUI Programming by Example
Tkinter GUI Programming by Example
Read more
Apr 2018340 pages
Full star icon1 (3)
eBook
eBook
₹799.99₹3276.99
₹4096.99
Stars icon
Total11,470.97
Tkinter GUI Application Development Blueprints, Second Edition
₹4096.99
Tkinter GUI Application Development Cookbook
₹3276.99
Tkinter GUI Programming by Example
₹4096.99
Total11,470.97Stars icon

Table of Contents

12 Chapters
Meet TkinterChevron down iconChevron up icon
Meet Tkinter
Installation
How will the code be structured?
Getting going
Adding interactivity
Using variables
Showing messages
Getting text input
Summary
Back to the Command Line – Basic BlackjackChevron down iconChevron up icon
Back to the Command Line – Basic Blackjack
Python's class system
Blackjack's classes
The Game class and main loop
Command line versus GUI
Summary
Jack is Back in Style – the Blackjack GUIChevron down iconChevron up icon
Jack is Back in Style – the Blackjack GUI
Moving from the command line to a graphical interface
The Canvas widget
Creating a graphical blackjack game
Playing our game
Summary
The Finishing Touches – Sound and AnimationChevron down iconChevron up icon
The Finishing Touches – Sound and Animation
Python's module system
The blackjack packages
The blackjack.py file
Summary
Creating a Highly Customizable Python EditorChevron down iconChevron up icon
Creating a Highly Customizable Python Editor
The ttk submodule
Beginning our text editor
Tkinter's event system
Events in our text editor
A second top-level window
Summary
Color Me Impressed! – Adding Syntax HighlightingChevron down iconChevron up icon
Color Me Impressed! – Adding Syntax Highlighting
Tkinter's indexing system
Using tags
Searching text
Adding syntax highlighting to our text editor
Summary
Not Just for Restaurants – All About MenusChevron down iconChevron up icon
Not Just for Restaurants – All About Menus
The Menu widget
Adding a menu bar to our text editor
Adding a context menu to our text editor
Handling files
Changing the syntax highlighting
Changing the editor's font
Changing the editor's color scheme
Summary
Talk Python to Me – a Chat ApplicationChevron down iconChevron up icon
Talk Python to Me – a Chat Application
Creating a scrollable frame
Creating our FriendsList class
Creating our ChatWindow class
Creating our SmilieSelect class
Summary
Connecting – Getting Our Chat Client OnlineChevron down iconChevron up icon
Connecting – Getting Our Chat Client Online
Introduction to flask
The requests module
The sqlite3 module
Linking flask and sqlite
Updating our FriendsList class
Creating the Requester class
Connecting our FriendsList to our web service
Connecting our ChatWindow
Summary
Making Friends – Finishing Our Chat ApplicationChevron down iconChevron up icon
Making Friends – Finishing Our Chat Application
Using threads
Adding a Thread to our ChatWindow
Allowing users to upload avatars
Adding and blocking other users
Summary
Wrapping Up – Packaging Our Applications to ShareChevron down iconChevron up icon
Wrapping Up – Packaging Our Applications to Share
Unexplored widgets
Packaging applications
Summary
Other Books You May EnjoyChevron down iconChevron up icon
Other Books You May Enjoy
Leave a review - let other readers know what you think

Recommendations for you

Left arrow icon
Debunking C++ Myths
Debunking C++ Myths
Read more
Dec 2024226 pages
Full star icon5 (1)
eBook
eBook
₹799.99₹2382.99
₹2978.99
Go Recipes for Developers
Go Recipes for Developers
Read more
Dec 2024350 pages
eBook
eBook
₹799.99₹2382.99
₹2978.99
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
₹799.99₹2978.99
₹3723.99
₹3723.99
Asynchronous Programming with C++
Asynchronous Programming with C++
Read more
Nov 2024424 pages
Full star icon5 (1)
eBook
eBook
₹799.99₹2502.99
₹3127.99
Modern CMake for C++
Modern CMake for C++
Read more
May 2024504 pages
Full star icon4.7 (12)
eBook
eBook
₹799.99₹2978.99
₹3723.99
Learn Python Programming
Learn Python Programming
Read more
Nov 2024616 pages
Full star icon5 (1)
eBook
eBook
₹799.99₹2382.99
₹2978.99
Learn to Code with Rust
Learn to Code with Rust
Read more
Nov 202457hrs 40mins
Video
Video
₹5585.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (21)
eBook
eBook
₹799.99₹3276.99
₹4096.99
Right arrow icon

Customer reviews

Rating distribution
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1
(3 Ratings)
5 star0%
4 star0%
3 star0%
2 star0%
1 star100%
VinceJan 29, 2021
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1
TROPPO DIFFICILE QUESTO LIBRO, SOLO LEGGENDOLO E RILEGGENDOLO PIU VOLTE ALLA FINE CI SI CAPISCE QUALCOSA. DA MOLTISSIME COSE PER SCONTATE, SICURAMENTE NON UNA GUIDA PER BEGGINERS. SECONDO ME RISULTA SCOMODO DA USARE ANCHE PER DEGLI ADVANCED.
Amazon Verified reviewAmazon
Stefan ZeeOct 13, 2021
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1
Variablen ändern sich während des Ablaufs, so dass man eher Fehler such anstatt Dinge zu lernen.Komplett zusammenhängende Code erhält man erst gegen Registrierung auf einer weiteren Website. Schade.
Amazon Verified reviewAmazon
ScifudJan 22, 2019
Full star iconEmpty star iconEmpty star iconEmpty star iconEmpty star icon1
This book was just what I was looking for with well explained examples, but as a Kindle book the examples are nearly useless. This is because python requires strict adherence to indentation but the way the text of the examples is displayed with the Kindle reader on my iPad the indentation is ambiguous. I spent several frustrating hours trying to determine if the errors my IDE was giving were due to improper code or to indentation. I got the first example to work by correcting an indentation error however the second example (a continuation of the first) creates an error that does not make sense.Until the code examples are formatted in a way that makes sense on Kindle I can not recommend this book in that form.I have returned the Kindle edition and have purchased the paperback. I will update this review after I have had a chance to review it.
Amazon Verified reviewAmazon

People who bought this also bought

Left arrow icon
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
₹799.99₹2978.99
₹3723.99
₹3723.99
Event-Driven Architecture in Golang
Event-Driven Architecture in Golang
Read more
Nov 2022384 pages
Full star icon4.9 (11)
eBook
eBook
₹799.99₹2978.99
₹3723.99
The Python Workshop Second Edition
The Python Workshop Second Edition
Read more
Nov 2022600 pages
Full star icon4.6 (22)
eBook
eBook
₹799.99₹3562.99
₹3872.99
Template Metaprogramming with C++
Template Metaprogramming with C++
Read more
Aug 2022480 pages
Full star icon4.6 (14)
eBook
eBook
₹799.99₹3220.99
₹3500.99
Domain-Driven Design with Golang
Domain-Driven Design with Golang
Read more
Dec 2022204 pages
Full star icon4.4 (19)
eBook
eBook
₹799.99₹2680.99
₹3351.99
Right arrow icon

About the author

Profile icon David Love
David Love
David Love is a web developer from Kent, England. He has worked on a multitude of different systems over his career. Programming languages in his arsenal include Python, PHP, and JavaScript. He is well-trained in Linux server management and its relevant technologies, including MySQL, PostgreSQL, NGINX, and supervisor. David has written an e-book called Tkinter By Example, which is available for free under a Creative Commons licenses and maintains an ever-growing blog post named The Tkinter Cookbook, full of small examples on how to perform some specific tasks.
Read more
See other products by David Love
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order?Chevron down iconChevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book?Chevron down iconChevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium:Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge?Chevron down iconChevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order?Chevron down iconChevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries:www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges?Chevron down iconChevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live inMexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live inTurkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order?Chevron down iconChevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy?Chevron down iconChevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged?Chevron down iconChevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use?Chevron down iconChevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books?Chevron down iconChevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium:Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela

[8]ページ先頭

©2009-2025 Movatter.jp