Tkinter Tutorial 6

Magic 8 GUI development






Lets look at the program in more detail

import random
import Tkinter # note use of caps
from Tkinter import *

The main difference here is the addition of the ramdom module otherwise we are importing Tkinter as before

#set up
window = Tk()
window.title('Magic 8')
window.geometry("300x100") #wxh

As before we define the window, you will notice I have made the
window size 300 x 100. This makes the window a nice size around
the program buttons and text entry / output boxes

We now define the responses we want and store these in an array

RESPONSES = ["It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it yes",
"Most likely",
"Outlook good",
"Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"]

As Discussed earlier functions get defined first so we now define a
function that calls up a random response from the array.

def response():
x = random.choice(RESPONSES)
#print x
circletext2.delete(0, END) # clear prev output

Note a few things here

x is a variable that now stores the responses

note I have commented out with a # print x, (this was used to test
and left in so it can be used later) uncomment while testing
your programs

The next line simply clears the out put text box
(keeps program tidy) you don’t need it but it keeps things
in good order. The next line does all the work, and inserts the
response variable x as a string (str)

Once this is done we can start with the actual gui design.

#define labels - cannot share same name as function
box1 = Label(window, text="Question: ")
box2 = Label(window, text="Answer: ")
#place labels
box1.grid(row = 1, column = 1, padx = 5, pady = 5)
box2.grid(row = 2, column = 1, padx = 5, pady = 5)
#define entry box
circleVar = StringVar()
circletext = Entry(window, textvariable=circleVar)
#define out box
circleVar2 = StringVar()
circletext2 = Entry(window, textvariable=circleVar2)
#display boxes
circletext.grid(row = 1, column = 2,)
circletext2.grid(row = 2, column = 2,)
#define buttons
response = Button( window, text ='respomse', command=response)
exitbtn = Button( window, text ='Exit', command=exit)
#place buttons
response.grid(row = 4, column = 1, padx = 1, pady = 1)
exitbtn.grid(row = 4, column = 2, padx = 1, pady = 1)
#display window

This should work you may find there are a few issues, mainly around what happens if we try and enter no question or enter random numbers however we can debug later

Curriculum links




Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress Anti Spam by WP-SpamShield