Text stringlengths 1 9.41k |
|---|
OBJECT-ORIENTED PROGRAMMING_
8. Write a class that inherits from the Card_group class of this chapter. |
The class should represent a deck of cards that contains only hearts and spaces, with only the cards 2 through 10
in each suit. |
Add a method to the class called next2 that returns the top two cards from the
deck.
9. Write a class called Rock_paper_scissors that implements the logic of the game Rockpaper-scissors. |
For this game the user plays against the computer for a certain number of
rounds. |
Your class should have fields for the how many rounds there will be, the current
round number, and the number of wins each player has. |
There should be methods for getting
the computer’s choice, finding the winner of a round, and checking to see if someone has one
the (entire) game. You may want more methods.
10. |
(a) Write a class called Connect4 that implements the logic of a Connect4 game. |
Use the
Tic_tac_toe class from this chapter as a starting point.
(b) Use the Connect4 class to create a simple text-based version of the game.
11. |
Write a class called Poker_hand that has a field that is a list of Card objects. |
There should be
the following self-explanatory methods:
has_royal_flush, has_straight_flush, has_four_of_a_kind,
has_full_house, has_flush, has_straight,
has_three_of_a_kind, has_two_pair, has_pair
There should also be a method called best that returns a string indicating what the best hand
is that can be made from t... |
But most real programs use windows, buttons, scrollbars,
and various other things. |
These widgets are part of what is called a Graphical User Interface or GUI.
This chapter is about GUI programming in Python with Tkinter.
All of the widgets we will be looking at have far more options than we could possibly cover here.
An excellent reference is Fredrik Lundh’s Introduction to Tkinter [2].
###### 15.1... |
The second line creates a
window on the screen, which we call root. The third line puts the program into what is essentially
a long-running while loop called the event loop. |
This loop runs, waiting for keypresses, button
clicks, etc., and it exits when the user closes the window.
Here is a working GUI program that converts temperatures from Fahrenheit to Celsius.
**from tkinter import ***
**def calculate():**
temp = int(entry.get())
temp = 9/5*temp+32
output_label.configure(text = 'Con... |
GUI PROGRAMMING WITH TKINTER_
root = Tk()
message_label = Label(text='Enter a temperature',
font=('Verdana', 16))
output_label = Label(font=('Verdana', 16))
entry = Entry(font=('Verdana', 16), width=4)
calc_button = Button(text='Ok', font=('Verdana', 16),
command=calculate)
message_label.grid(row=0, column=0)
entr... |
The following code creates a
label and places it on the screen.
hello_label = Label(text='hello')
hello_label.grid(row=0, column=0)
We call Label to create a new label. The capital L is required. |
Our label’s name is hello_label.
Once created, use the grid method to place the label on the screen. |
We will explain grid in the
next section.
**Options** There are a number of options you can change including font size and color. |
Here are
some examples:
hello_label = Label(text='hello', font=('Verdana', 24, 'bold'),
bg='blue', fg='white')
Note the use of keyword arguments. |
Here are a few common options:
- font — The basic structure is font= (font name, font size, style). You can leave out the font
size or the style. |
The choices for style are 'bold', 'italic', 'underline', 'overstrike',
'roman', and 'normal' (which is the default). You can combine multiple styles like this:
'bold italic'.
-----
_15.3. |
GRID_ 145
- fg and bg — These stand for foreground and background. Many common color names
can be used, like 'blue', 'green', etc. |
Section 16.2 describes how to get essentially any
color.
- width — This is how many characters long the label should be. |
If you leave this out, Tkinter
will base the width off of the text you put in the label. |
This can make for unpredictable results,
so it is good to decide ahead of time how long you want your label to be and set the width
accordingly.
- height — This is how many rows high the label should be. |
You can use this for multiline labels. Use newline characters in the text to get it to span multiple lines. For example,
text='hi\nthere'.
There are dozens more options. |
The aforementioned Introduction to Tkinter [2] has a nice list of the
others and what they do.
**Changing label properties** Later in your program, after you’ve created a label, you may want to
change something about it. |
To do that, use its configure method. |
Here are two examples that
change the properties of a label called label:
label.configure(text='Bye')
label.configure(bg='white', fg='black')
Setting text to something using the configure method is kind of like the GUI equivalent of a
**print statement. |
However, in calls to configure we cannot use commas to separate multiple**
things to print. We instead need to use string formatting. |
Here is a print statement and its equivalent using the configure method.
**print('a =', a, 'and b =', b)**
label.configure(text='a = {}, and b = {}'.format(a,b))
The configure method works with most of the other widgets we will see.
###### 15.3 grid
The grid method is used to place things on the screen. |
It lays out the screen as a rectangular grid
of rows and columns. |
The first few rows and columns are shown below.
###### (row=0, column=0) (row=0, column=1) (row=0, column=2)
(row=1, column=0) (row=1, column=1) (row=1, column=2)
(row=2, column=0) (row=2, column=1) (row=2, column=2)
**Spanning multiple rows or columns** There are optional arguments, rowspan and columnspan,
that al... |
Here is an example of several grid
statements followed by what the layout will look like:
|(row=0, column=0)|(row=0, column=1)|(row=0, column=2)|
|---|---|---|
|(row=1, column=0)|(row=1, column=1)|(row=1, column=2)|
|(row=2, column=0)|(row=2, column=1)|(row=2, column=2)|
-----
146 _CHAPTER 15. |
GUI PROGRAMMING WITH TKINTER_
label1.grid(row=0, column=0)
label2.grid(row=0, column=1)
label3.grid(row=1, column=0, columnspan=2)
label4.grid(row=1, column=2)
label5.grid(row=2, column=2)
###### label1 label2
label 3 label4 label5
**Spacing** To add extra space between widgets, there are optional arguments padx an... |
Otherwise it will not be visible.
###### 15.4 Entry boxes
Entry boxes are a way for your GUI to get text input. |
The following example creates a simple entry
box and places it on the screen.
entry = Entry()
entry.grid(row=0, column=0)
Most of the same options that work with labels work with entry boxes (and most of the other
widgets we will talk about). |
The width option is particularly helpful because the entry box will
often be wider than you need.
- Getting text To get the text from an entry box, use its get method. |
This will return a string.
If you need numerical data, use eval (or int or float) on the string. |
Here is a simple
example that gets text from an entry box named entry.
string_value = entry.get()
num_value = eval(entry.get())
- Deleting text To clear an entry box, use the following:
|label1|label2|Col3|
|---|---|---|
|label 3||label4|
|||label5|
entry.delete(0,END)
- Inserting text To insert text into an ... |
BUTTONS_ 147
ok_button = Button(text='Ok')
To get the button to do something when clicked, use the command argument. It is set to the name
of a function, called a callback function. |
When the button is clicked, the callback function is called.
Here is an example:
**from tkinter import ***
**def callback():**
label.configure(text='Button clicked')
root = Tk()
label = Label(text='Not clicked')
button = Button(text='Click me', command=callback)
label.grid(row=0, column=0)
button.grid(row=1, colum... |
When the button is clicked, the callback function callback is called, which changes the label to say Button clicked.
###### lambda trick Sometimes we will want to pass information to the callback function, like if we
have several buttons that use the same callback function and we want to give the function information ... |
Here is an example where we create 26 buttons, one
for each letter of the alphabet. |
Rather than use 26 separate Button() statements and 26 different
functions, we use a list and one function.
|get the button to do something when clicked, use the command argument. |
It is set to the name a function, called a callback function. When the button is clicked, the callback function is called. |
re is an example:|Col2|
|---|---|
|||
|from tkinter import * def callback(): label.configure(text='Button clicked') root = Tk() label = Label(text='Not clicked') button = Button(text='Click me', command=callback) label.grid(row=0, column=0) button.grid(row=1, column=0) mainloop()||
|mbda trick Sometimes we will want t... |
Here is an example where we create 26 buttons, one each letter of the alphabet. |
Rather than use 26 separate Button() statements and 26 different ctions, we use a list and one function.|Col2|
|---|---|
|||
|from tkinter import * alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def callback(x): label.configure(text='Button {} clicked'.format(alphabet[x])) root = Tk() label = Label() label.grid(row=1, column=... |
GUI PROGRAMMING WITH TKINTER_
buttons[i].grid(row=0, column=i)
mainloop()
We note a few things about this program. First, we set buttons=[0]*26. This creates a list with 26
things in it. |
We don’t really care what thoset things are because they will be replaced with buttons.
An alternate way to create the list would be to set buttons=[] and use the append method.
We only use one callback function and it has one argument, which indicates which button was
clicked. |
As far as the lambda trick goes, without getting into the details, command=callback(i)
does not work, and that is why we resort to the lambda trick. You can read more about lambda in
Section 23.2. |
An alternate approach is to use classes.
###### 15.6 Global variables
Let’s say we want to keep track of how many times a button is clicked. |
An easy way to do this is to
use a global variable as shown below.
**from tkinter import ***
**def callback():**
**global num_clicks**
num_clicks = num_clicks + 1
label.configure(text='Clicked {} times.'.format(num_clicks))
num_clicks = 0
root = Tk()
label = Label(text='Not clicked')
button = Button(text='Click me... |
Using global variables unnecessarily,
especially in long programs, can cause difficult to find errors that make programs hard to maintain,
|’s say we want to keep track of how many times a button is clicked. |
An easy way to do this is to a global variable as shown below.|Col2|
|---|---|
|||
|from tkinter import * def callback(): global num_clicks num_clicks = num_clicks + 1 label.configure(text='Clicked {} times.'.format(num_clicks)) num_clicks = 0 root = Tk() label = Label(text='Not clicked') button = Button(text='Click me... |
TIC-TAC-TOE_ 149
but in the short programs that we will be writing, we should be okay. |
Object-oriented programming
provides an alternative to global variables.
###### 15.7 Tic-tac-toe
Using Tkinter, in only about 20 lines we can make a working tic-tac-toe program:
**from tkinter import ***
**def callback(r,c):**
**global player**
**if player == 'X':**
b[r][c].configure(text = 'X')
player = 'O'
**e... |
We will fix this shortly. First, let’s look at how the program does what it does.
Starting at the bottom, we have a variable player that keeps track of whose turn it is. |
Above that
we create the board, which consists of nine buttons stored in a two-dimensional list. We use the
**lambda trick to pass the row and column of the clicked button to the callback function. |
In the**
callback function we write an X or an O into the button that was clicked and change the value of
the global variable player.
|Col1|Col2|
|---|---|
|from tkinter import * def callback(r,c): global player if player == 'X': b[r][c].configure(text = 'X') player = 'O' else: b[r][c].configure(text = 'O') player = '... |
GUI PROGRAMMING WITH TKINTER_
**Correcting the problems** To correct the problem about being able to change a cell that already
has something in it, we need to have a way of knowing which cells have X’s, which have O’s, and
which are empty. |
One way is to use a Button method to ask the button what its text is. |
Another
way, which we will do here is to create a new two-dimensional list, which we will call states, that
will keep track of things. |
Here is the code.
|rrecting the problems To correct the problem about being able to change a cell that already something in it, we need to have a way of knowing which cells have X’s, which have O’s, and ich are empty. |
One way is to use a Button method to ask the button what its text is. Another y, which we will do here is to create a new two-dimensional list, which we will call states, that l keep track of things. |
Here is the code.|Col2|
|---|---|
|||
|from tkinter import * def callback(r,c): global player if player == 'X' and states[r][c] == 0: b[r][c].configure(text='X') states[r][c] = 'X' player = 'O' if player == 'O' and states[r][c] == 0: b[r][c].configure(text='O') states[r][c] = 'O' player = 'X' root = Tk() states = [[0,0... |
TIC-TAC-TOE_ 151
player = 'X'
mainloop()
We have not added much to the program. |
Most of the new action happens in the callback function.
Every time someone clicks on a cell, we first check to see if it is empty (that the corresponding index
in states is 0), and if it is, we display an X or O on the screen and record the new value in states.
Many games have a variable like states that keeps track o... |
To check if there are three in a row across the top row, we can
use the following if statement:
**if states[0][0]==states[0][1]==states[0][2]!=0:**
stop_game=True
b[0][0].configure(bg='grey')
b[0][1].configure(bg='grey')
b[0][2].configure(bg='grey')
This checks to see if each of the cells has the same nonzero entr... |
We are using the shortcut from
Section 10.3 here in the if statement. There are more verbose if statements that would work. |
If we
do find a winner, we highlight the winning cells and then set a global variable stop_game equal to
**True. This variable will be used in the callback function. |
Whenever the variable is True we should**
not allow any moves to take place.
Next, to check if there are three in a row across the middle row, change the first coordinate from 0
to 1 in all three references, and to check if there are three in a row across the bottom, change the 0’s
to 2’s. |
Since we will have three very similar if statements that only differ in one location, a for loop
can be used to keep the code short:
**for i in range(3):**
**if states[i][0]==states[i][1]==states[i][2]!=0:**
b[i][0].configure(bg='grey')
b[i][1].configure(bg='grey')
b[i][2].configure(bg='grey')
stop_game = True
Nex... |
Finally, we have two further if statements to take care of the diagonals. The full
program is at the end of this chapter. |
We have also added a few color options to the configure
statements to make the game look a little nicer.
**Further improvements** From here it would be easy to add a restart button. |
The callback function
for that variable should set stop_game back to false, it should set states back to all zeroes, and it
should configure all the buttons back to text='' and bg='yellow'.
To add a computer player would also not be too difficult, if you don’t mind it being a simple com
-----
152 _CHAPTER 15. |
GUI PROGRAMMING WITH TKINTER_
puter player that moves randomly. That would take about 10 lines of code. To make an intelligent
computer player is not too difficult. |
Such a computer player should look for two O’s or X’s in a
row in order to try to win or block, as well avoid getting put into a no-win situation.
|er player that moves randomly. |
That would take about 10 lines of code. To make an intelligent mputer player is not too difficult. |
Such a computer player should look for two O’s or X’s in a w in order to try to win or block, as well avoid getting put into a no-win situation.|Col2|
|---|---|
|||
|from tkinter import * def callback(r,c): global player if player == 'X' and states[r][c] == 0 and stop_game==False: b[r][c].configure(text='X', fg='blue',... |
TIC-TAC-TOE_ 153
-----
154 _CHAPTER 15. |
GUI PROGRAMMING WITH TKINTER_
-----
### Chapter 16
## GUI Programming II
In this chapter we cover more basic GUI concepts.
###### 16.1 Frames
Let’s say we want 26 small buttons across the top of the screen, and a big Ok button below them,
like below:
We try the following code:
**from tkinter import ***
root ... |
GUI PROGRAMMING II_
The problem is with column 0. There are two widgets there, the A button and the Ok button, and
Tkinter will make that column big enough to handle the larger widget, the Ok button. |
One solution
to this problem is shown below:
ok_button.grid(row=1, column=0, columnspan=26)
Another solution to this problem is to use what is called a frame. |
The frame’s job is to hold other
widgets and essentially combine them into one large widget. In this case, we will create a frame to
group all of the letter buttons into one large widget. |
The code is shown below:
**from tkinter import ***
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
root = Tk()
button_frame = Frame()
buttons = [0]*26
**for i in range(26):**
buttons[i] = Button(button_frame, text=alphabet[i])
buttons[i].grid(row=0, column=i)
ok_button = Button(text='Ok', font=('Verdana', 24))
button_fra... |
Then, for any widgets we want include in
the frame, we include the name of the frame as the first argument in the widget’s declaration. |
We
still have to grid the widgets, but now the rows and columns will be relative to the frame. |
Finally,
we have to grid the frame itself.
###### 16.2 Colors
Tkinter defines many common color names, like 'yellow' and 'red'. It also provides a way to
get access to millions of more colors. |
We first have to understand how colors are displayed on the
screen.
Each color is broken into three components—a red, a green, and a blue component. |
Each component can have a value from 0 to 255, with 255 being the full amount of that color. |
Equal parts of red
and green create shades of yellow, equal parts of red and blue create shades of purple, and equal
|other solution to this problem is to use what is called a frame. |
The frame’s job is to hold other dgets and essentially combine them into one large widget. In this case, we will create a frame to up all of the letter buttons into one large widget. |
The code is shown below:|Col2|
|---|---|
|||
|from tkinter import * alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' root = Tk() button_frame = Frame() buttons = [0]*26 for i in range(26): buttons[i] = Button(button_frame, text=alphabet[i]) buttons[i].grid(row=0, column=i) ok_button = Button(text='Ok', font=('Verdana', 24)) but... |
IMAGES_ 157
parts of blue and green create shades of turquoise. |
Equal parts of all three create shades of gray.
Black is when all three components have values of 0 and white is when all three components have
values of 255. |
Varying the values of the components can produce up to 256[3] 16 million colors.
_≈_
There are a number of resources on the web that allow you to vary the amounts of the components
and see what color is produced.
To use colors in Tkinter is easy, but with one catch—component values are given in hexadecimal.
Hexadecima... |
It was widely used in the early days of computing, and it is still used here and there.
Here is a table comparing the two number bases:
0 0 8 8 16 10 80 50
1 1 9 9 17 11 100 64
2 2 10 A 18 12 128 80
3 3 11 B 31 1F 160 A0
4 4 12 C 32 20 200 C8
5 5 13 D 33 21 254 FE
6 6 14 E 48 30 255 FF
7 7 15 F 64 40 256 100
Because ... |
A typical color in Tkinter is specified like this:
'#A202FF'. The color name is prefaced with a pound sign. Then the first two digits are the red
component (in this case A2, which is 162 in decimal). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.