Ok heres the deal they're both a mathematics program but i want to make it like this...

from Tkinter import *
import tkMessageBox
import random

def ask():
    global num1 
    num1 = random.randint(1, 100)
    global num2 
    num2 = random.randint(1, 100)
    global answer 
    answer = num1 + num2
    label1.config(text='What is ' + str(num1) + '+' + str(num2) + '?')

    # put the cursor into the Enter-Box
    entry1.focus_set()
    
def checkAnswer():
    mainAnswer = entry1.get()
    
    # if empty give message
    if len(mainAnswer) == 0:
        tkMessageBox.showwarning(message='Need to enter some numbers!')
        return
    if int(mainAnswer) != answer:
        tkMessageBox.showwarning(message='The correct answer is: ' + str(answer))
    else:
        tkMessageBox.showinfo(message='Correct! :)')

#set the window
root = Tk()
root.title("Mikey's Multiplication Quiz")
root.geometry('500x500')

# welcome message
label2 = Label(root, text="Hi!\n  Let's do some Mathematics problems!")
label2.config(font=('times', 18, 'bold'), fg='black', bg='white')
label2.grid(row=0, column=0)

#add label
label1 = Label(root)
label1.grid(row=2, column=0)

#entry
entry1 = Entry(root)
entry1.grid(row=3, column=0)

# bind the return key
entry1.bind('<Return>', func=lambda e:checkAnswer())

#button
askBtn = Button(root, text='Ask Me a Question!', command=ask)
askBtn.grid(row=4, column=0)

okButton = Button(root, text='OK', command=checkAnswer)
okButton.grid(row=4, column=1)

root.mainloop()

and from this code below implement it to like the one above ^^^^

name = raw_input("\t\t\tPlease Enter Your Name: ")

print
print "\t\t\t\tHello", name
print "\t\t\tWelcome to my Mathematics Game"

# Selecting the operation of Addition and Substraction followed by the difficulty
print
operation = str(raw_input("\t\t\tAddition (A) or Substraction (S)"))
if operation == "A" or operation == "a":
    my_op = 'Add'
    difficulty = str(raw_input("\tSelect a difficulty - Easy (E)(1-100), Medium (M) (1-200) or Hard (H) (1-500)"))
    print
    print "Addition"
    print '** ** **'
    print
elif operation == "S" or operation == "s":
    my_op = 'Sub'
    difficulty = str(raw_input("\tSelect a difficulty - Easy (E)(1-100), Medium (M) (1-200) or Hard (H) (1-500)"))
    print
    print "Subtraction"
    print '** ** ** **'
    print

if difficulty == "Easy" or difficulty == "easy" or difficulty == "E" or difficulty == "e":
    my_rand_range = 100
elif difficulty == "Medium" or difficulty == "medium" or difficulty == "M" or difficulty == "m":
    my_rand_range = 200
elif difficulty == "Hard" or difficulty == "hard" or difficulty == "H" or difficulty == "h":
    my_rand_range = 500

# Amount of questions asked (10) and randomisation of numbers
import random
counter = 0
while counter < 10:
    counter = counter +1

    # Difficulty - Easy, Medium or Hard
    number1 = random.randrange( my_rand_range ) + 1
    number2 = random.randrange( my_rand_range ) + 1

    # Addition Calculations
    if my_op == 'Add':
        print number1, "+", number2, "="
    # Substraction Calculations
    elif my_op == 'Sub':
        print number1, "-", number2, "="

    # Input for answer
    answer = int(raw_input("Type in your answer: "))

    # If Its "Correct" or "Incorrect"
    if ( answer == number1 + number2 and my_op == 'Add' ) or \
        ( answer == number1 - number2 and my_op == 'Sub' ):
        print "Correct :)"
        print
    else:
        print "Incorrect :("
        print

raw_input("\n\nPress the enter key to exit.")

see i want code number 2 to look like code number 1 somehow

Please can anyone figure this out

thanks

Recommended Answers

All 12 Replies

hello here
I have got one question.I would like to write a program that deals with Wordnet and Wikipedia.For example i take a word "glass"then there are four artikcle on it but from them only one article has similarity with the synsets of wordnet and that I want to do it with using tf-idf weight(term frequency-inverse document frequency).Can someone help me please?

riyadhmehmood, do not hijack somebody elses thread! Very bad manners. Start your own thread.

MikeyFTW,
looks like you have to study up on Tkinter GUI programming.

Here is an introduction:
http://www.pythonware.com/library/tkinter/introduction/index.htm

In simple terms, create a frame/window/root, input through an Entry, action with a Button and output to a Label.

please man can you do an example for me so i can learn off towards my program

Okay, here is a simple create a window, input through an Entry, action with a Button and output to a Label code example:

# a simple Tkinter number guessing game
# shows how to create a window, an entry, a label, a button,
# a button mouse click response, and how to use a grid for layout

from Tkinter import *
import random

def click():
    """the mouse click command response"""
    global rn
    # get the number from the entry area
    num = int(enter1.get())
    # check it out
    if num > rn:
        label2['text'] = str(num) + " guessed too high!"
    elif num < rn:
        label2['text'] = str(num) + " guessed too low!"
    else:
        s1 = str(num) + " guessed correctly!"
        s2 = "\n Let's start a new game!"
        label2['text'] = s1 + s2
        # pick a new random number
        rn = random.randrange(1, 11)
    enter1.delete(0, 2)


# create the window and give it a title
root = Tk()
root.title("Heidi's Guess A Number Game")

# pick a random integer from 1 to 10
rn = random.randrange(1, 11)

# let the user know what is going on
label1 = Label(root, text="Guess a number between 1 and 10 -->")
# layout this label in the specified row and column of the grid
# also pad with spaces along the x and y direction
label1.grid(row=1, column=1, padx=10, pady=10)

# this your input area
enter1 = Entry(root, width=5, bg='yellow')
enter1.grid(row=1, column=2, padx=10)
# put the cursor into the entry field
enter1.focus()

# this is your mouse action button, right-click it to execute command
button1 = Button(root, text=" Press to check the guess ", command=click)
button1.grid(row=2, column=1, columnspan=2, padx=10, pady=10)

# the result displays here
label2 = Label(root, text="", width=50)
label2.grid(row=3, column=1, columnspan=2, pady=10)

# start the mouse/keyboard event loop
root.mainloop()

GUI programming takes a moment to get used to!

Okay, here is a simple create a window, input through an Entry, action with a Button and output to a Label code example:

# a simple Tkinter number guessing game
# shows how to create a window, an entry, a label, a button,
# a button mouse click response, and how to use a grid for layout

from Tkinter import *
import random

def click():
    """the mouse click command response"""
    global rn
    # get the number from the entry area
    num = int(enter1.get())
    # check it out
    if num > rn:
        label2['text'] = str(num) + " guessed too high!"
    elif num < rn:
        label2['text'] = str(num) + " guessed too low!"
    else:
        s1 = str(num) + " guessed correctly!"
        s2 = "\n Let's start a new game!"
        label2['text'] = s1 + s2
        # pick a new random number
        rn = random.randrange(1, 11)
    enter1.delete(0, 2)


# create the window and give it a title
root = Tk()
root.title("Heidi's Guess A Number Game")

# pick a random integer from 1 to 10
rn = random.randrange(1, 11)

# let the user know what is going on
label1 = Label(root, text="Guess a number between 1 and 10 -->")
# layout this label in the specified row and column of the grid
# also pad with spaces along the x and y direction
label1.grid(row=1, column=1, padx=10, pady=10)

# this your input area
enter1 = Entry(root, width=5, bg='yellow')
enter1.grid(row=1, column=2, padx=10)
# put the cursor into the entry field
enter1.focus()

# this is your mouse action button, right-click it to execute command
button1 = Button(root, text=" Press to check the guess ", command=click)
button1.grid(row=2, column=1, columnspan=2, padx=10, pady=10)

# the result displays here
label2 = Label(root, text="", width=50)
label2.grid(row=3, column=1, columnspan=2, pady=10)

# start the mouse/keyboard event loop
root.mainloop()

GUI programming takes a moment to get used to!

Oh cool thanks man this really gave me the idea for my program and i learned alot of how GUI works on my way through as well.

Thanks mate! :)

But i may need some help from you soon lol

Ok man i am seriously stuck now...

First problem - i cant get the "name input" to work, i have no idea what the code is, i want it to say "Hello, (name)" just below the "OK" button when the user inputs there name and clicks OK.

Second problem - When the user chooses which operation they want, i want it to go to a completely different window for each operation which ive done BUT how do you make it show it in the acutal window???

Any other help will also be appreciated! :)

from Tkinter import *
import random

# create the window and give it a title
root = Tk()
root.title("Main Menu - Mathematics Quiz")
root.geometry('500x300')

def Click():  


# let the user know what is going on
label1 = Label(root, text="Please Enter Your Name: ")
label1.grid(row=0, column=1, padx=10, pady=10)

# this your input area
enter1 = Entry(root, width=15, bg='Green')
enter1.grid(row=1, column=1, padx=10)

# the result displays here
label2 = Label(root, text="", width=50)
label2.grid(row=3, column=1, columnspan=1, pady=10)

# put the cursor into the entry field
enter1.focus()

# this is your mouse action button, right-click it to execute command
button1 = Button(root, text=" OK ", command=Click)
button1.grid(row=2, column=1, columnspan=1, padx=10, pady=10)

# the result displays here
label3 = Label(root, text="Please Select Your Option From Below: ", width=50)
label3.grid(row=4, column=1, columnspan=1, pady=10)

#add label
label4 = Label(root)
label4.grid(row=9, column=1)

def Addition1():
    # create the window and give it a title
    root = Tk()
    root.title("Addition 1-100")
    root.geometry('500x300')
    global num1 
    num1 = random.randint(1, 100)
    global num2 
    num2 = random.randint(1, 100)
    global answer 
    answer = num1 + num2
    label4.config(text='What is ' + str(num1) + '+' + str(num2) + '?')

def Addition2():
    # create the window and give it a title
    root = Tk()
    root.title("Addition 1-200")
    root.geometry('500x300')
    global num3 
    num3 = random.randint(1, 200)
    global num4 
    num4 = random.randint(1, 200)
    global answer 
    answer = num3 + num4
    label4.config(text='What is ' + str(num3) + '+' + str(num4) + '?')

def Addition3():
    # create the window and give it a title
    root = Tk()
    root.title("Addition 1-500")
    root.geometry('500x300')
    global num5 
    num5 = random.randint(1, 500)
    global num6 
    num6 = random.randint(1, 500)
    global answer 
    answer = num5 + num6
    label4.config(text='What is ' + str(num5) + '+' + str(num6) + '?')

def Substraction1():
    # create the window and give it a title
    root = Tk()
    root.title("Substraction (1-100)")
    root.geometry('500x300')
    global num7 
    num7 = random.randint(1, 100)
    global num8 
    num8 = random.randint(1, 100)
    global answer 
    answer = num7 - num8
    label4.config(text='What is ' + str(num7) + '-' + str(num8) + '?')

def Substraction2():
    # create the window and give it a title
    root = Tk()
    root.title("Substraction (1-200)")
    root.geometry('500x300')
    global num9 
    num9 = random.randint(1, 200)
    global num10 
    num10 = random.randint(1, 200)
    global answer 
    answer = num9 - num10
    label4.config(text='What is ' + str(num9) + '-' + str(num10) + '?')

def Substraction3():
    # create the window and give it a title
    root = Tk()
    root.title("Substraction (1-500)")
    root.geometry('500x300')
    global num11 
    num11 = random.randint(1, 500)
    global num12 
    num12 = random.randint(1, 500)
    global answer 
    answer = num11 - num12
    label4.config(text='What is ' + str(num11) + '-' + str(num12) + '?')

def Abouttheprogram():
    # create the window and give it a title
    root = Tk()
    root.title("About The Program")
    root.geometry('500x300')

def Abouttheauthor():
    # create the window and give it a title
    root = Tk()
    root.title("About The Author")
    root.geometry('500x300')
    
def Help():
    # create the window and give it a title
    root = Tk()
    root.title("Help")
    root.geometry('500x300')

def Exit():
    raw_input("\nPress enter key to exit. ")

# operation options 1
Add1Button = Button(root, text='Additon\n (1-100)', bg='Green', command=Addition1)
Add1Button.grid(row=5, column=0)

# 2
Add2Button = Button(root, text='Additon\n (1-200)', bg='Green', command=Addition2)
Add2Button.grid(row=5, column=1)

# 3
Add3Button = Button(root, text='Additon\n (1-500)', bg='Green', command=Addition3)
Add3Button.grid(row=5, column=2)

# 4
Sub1Button = Button(root, text='Substraction\n (1-100)', bg='Green', command=Substraction1)
Sub1Button.grid(row=6, column=0)

# 5
Sub2Button = Button(root, text='Substraction\n (1-200)', bg='Green', command=Substraction2)
Sub2Button.grid(row=6, column=1)

# 6
Sub3Button = Button(root, text='Substraction\n (1-500)', bg='Green', command=Substraction3)
Sub3Button.grid(row=6, column=2)

# About The Program Button
ProButton = Button(root, text='About The Program', bg='Green', command=Abouttheprogram)
ProButton.grid(row=8, column=0)

# About The Author Button
AutButton = Button(root, text='About The Author', bg='Green', command=Abouttheauthor)
AutButton.grid(row=9, column=0)

# Help Button
HelpButton = Button(root, text='Help', bg='Green', command=Help)
HelpButton.grid(row=8, column=2)

# Exit Button
ExitButton = Button(root, text='Exit', bg='Green', command=Exit)
ExitButton.grid(row=9, column=2)

# start the mouse/keyboard event loop
root.mainloop()

Recommended style for Python code is capitalized names for class names and non-capitalized names for functions.

Don't let def click(): dangle in space, use at least a ...

def click():
    pass

.. until you fill it in with your code.

Your prograsm can only have one main window or root window. If you want other windows to pop up you have to use child windows ...

# display message in a child window

from Tkinter import *

def messageWindow(message):
    # create child window
    win = Toplevel()
    # display message
    Label(win, text=message).pack()
    # quit child window and return to root window
    Button(win, text='OK', command=win.destroy).pack()

def createMessage():
    global counter
    counter = counter + 1
    message = "This is message number " + str(counter)
    messageWindow(message)

counter = 0
    
# create root window
root = Tk()
# put a button on it, command executes the given function on button-click
Button(root, text='Bring up Message', command=createMessage).pack()
# start event-loop
root.mainloop()

... or dialog windows like ...

# use Tkinter popup dialogs for input

from Tkinter import *
from tkSimpleDialog import askfloat  # also askinteger, askstring

def get_data():
    miles = askfloat('Miles', 'Enter miles driven')
    petrol = askfloat('Petrol', 'Enter gallon of petrol consumed')
    str1 = "Your milage is %0.2f miles/gallon" % (miles/petrol)
    var1.set(str1) 

root = Tk()
var1 = StringVar()

button1 = Button(root, text="Get data", command=get_data).pack(pady=5)
label1 = Label(root, textvariable=var1).pack()

root.mainloop()

Looks like you are well on the way of learning the GUI ropes!

An approach like this would simplify your game, taking advantage of some of the GUI features ...

from Tkinter import *
from tkSimpleDialog import askinteger  # also has askfloat, askstring
import random

def get_number(title="Integer Entry", prompt="Enter a number: "):
    return askinteger(title, prompt)

def addition1():
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    answer = num1 + num2
    myprompt = 'What is ' + str(num1) + '+' + str(num2) + '?'
    ask_player(answer, myprompt)

def addition2():
    num1 = random.randint(1, 200)
    num2 = random.randint(1, 200)
    answer = num1 + num2
    myprompt = 'What is ' + str(num1) + '+' + str(num2) + '?'
    ask_player(answer, myprompt)

def addition3():
    num1 = random.randint(1, 500)
    num2 = random.randint(1, 500)
    answer = num1 + num2
    myprompt = 'What is ' + str(num1) + '+' + str(num2) + '?'
    ask_player(answer, myprompt)

def subtraction1():
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    answer = num1 - num2
    myprompt = 'What is ' + str(num1) + '-' + str(num2) + '?'
    ask_player(answer, myprompt)

def subtraction2():
    num1 = random.randint(1, 200)
    num2 = random.randint(1, 200)
    answer = num1 - num2
    myprompt = 'What is ' + str(num1) + '-' + str(num2) + '?'
    ask_player(answer, myprompt)

def subtraction3():
    num1 = random.randint(1, 500)
    num2 = random.randint(1, 500)
    answer = num1 - num2
    myprompt = 'What is ' + str(num1) + '-' + str(num2) + '?'
    ask_player(answer, myprompt)

def ask_player(answer, myprompt):
    name = enter1.get()
    # use a default name if none is given
    if not name:
        name = "Player"
    attempt = 1
    while True:
        myanswer = get_number(prompt=myprompt)
        if myanswer == answer:
            label4.config(text=name + ", you are correct!")
            break
        if attempt >= 3:
            label4.config(text=name + ", you used up your 3 attempts!")
            break
        label4.config(text=str(attempt) + ": Not correct! Try again!")
        attempt += 1

# create the window and give it a title
# the root window will expand to accomodate all
root = Tk()
root.title("Main Menu - Mathematics Quiz")
root.configure(bg='beige')

# ask for the player's name
# Label and Entry
label1 = Label(root, text="Please Enter Your\n Name Below:", bg='beige')
label1.grid(row=0, column=2, pady=5)
enter1 = Entry(root, width=15, bg='green')
enter1.grid(row=1, column=2, pady=5)

# create your ops buttons
Add1Button = Button(root, text=' Addition \n (1-100)', bg='green',
    width=15, command=addition1)
Add1Button.grid(row=2, column=0, padx=5)

Add1Button = Button(root, text=' Addition \n (1-200)', bg='green',
    width=15, command=addition2)
Add1Button.grid(row=2, column=1, padx=5)

Add1Button = Button(root, text=' Addition \n (1-500)', bg='green',
    width=15, command=addition3)
Add1Button.grid(row=2, column=2, padx=5)

Sub1Button = Button(root, text=' Subtraction \n (1-100)', bg='green',
    width=15, command=subtraction1)
Sub1Button.grid(row=2, column=3, padx=5)

Sub2Button = Button(root, text=' Subtraction \n (1-200)', bg='green',
    width=15, command=subtraction2)
Sub2Button.grid(row=2, column=4, padx=5)

Sub3Button = Button(root, text=' Subtraction \n (1-500)', bg='green',
    width=15, command=subtraction3)
Sub3Button.grid(row=2, column=5, padx=5)

# create an output label
label4 = Label(root, text='------------', bg='beige')
label4.grid(row=3, column=4, columnspan=2, pady=10)

# start the mouse/keyboard event loop
root.mainloop()

An approach like this would simplify your game, taking advantage of some of the GUI features ...

from Tkinter import *
from tkSimpleDialog import askinteger  # also has askfloat, askstring
import random

def get_number(title="Integer Entry", prompt="Enter a number: "):
    return askinteger(title, prompt)

def addition1():
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    answer = num1 + num2
    myprompt = 'What is ' + str(num1) + '+' + str(num2) + '?'
    ask_player(answer, myprompt)

def addition2():
    num1 = random.randint(1, 200)
    num2 = random.randint(1, 200)
    answer = num1 + num2
    myprompt = 'What is ' + str(num1) + '+' + str(num2) + '?'
    ask_player(answer, myprompt)

def addition3():
    num1 = random.randint(1, 500)
    num2 = random.randint(1, 500)
    answer = num1 + num2
    myprompt = 'What is ' + str(num1) + '+' + str(num2) + '?'
    ask_player(answer, myprompt)

def subtraction1():
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    answer = num1 - num2
    myprompt = 'What is ' + str(num1) + '-' + str(num2) + '?'
    ask_player(answer, myprompt)

def subtraction2():
    num1 = random.randint(1, 200)
    num2 = random.randint(1, 200)
    answer = num1 - num2
    myprompt = 'What is ' + str(num1) + '-' + str(num2) + '?'
    ask_player(answer, myprompt)

def subtraction3():
    num1 = random.randint(1, 500)
    num2 = random.randint(1, 500)
    answer = num1 - num2
    myprompt = 'What is ' + str(num1) + '-' + str(num2) + '?'
    ask_player(answer, myprompt)

def ask_player(answer, myprompt):
    name = enter1.get()
    # use a default name if none is given
    if not name:
        name = "Player"
    attempt = 1
    while True:
        myanswer = get_number(prompt=myprompt)
        if myanswer == answer:
            label4.config(text=name + ", you are correct!")
            break
        if attempt >= 3:
            label4.config(text=name + ", you used up your 3 attempts!")
            break
        label4.config(text=str(attempt) + ": Not correct! Try again!")
        attempt += 1

# create the window and give it a title
# the root window will expand to accomodate all
root = Tk()
root.title("Main Menu - Mathematics Quiz")
root.configure(bg='beige')

# ask for the player's name
# Label and Entry
label1 = Label(root, text="Please Enter Your\n Name Below:", bg='beige')
label1.grid(row=0, column=2, pady=5)
enter1 = Entry(root, width=15, bg='green')
enter1.grid(row=1, column=2, pady=5)

# create your ops buttons
Add1Button = Button(root, text=' Addition \n (1-100)', bg='green',
    width=15, command=addition1)
Add1Button.grid(row=2, column=0, padx=5)

Add1Button = Button(root, text=' Addition \n (1-200)', bg='green',
    width=15, command=addition2)
Add1Button.grid(row=2, column=1, padx=5)

Add1Button = Button(root, text=' Addition \n (1-500)', bg='green',
    width=15, command=addition3)
Add1Button.grid(row=2, column=2, padx=5)

Sub1Button = Button(root, text=' Subtraction \n (1-100)', bg='green',
    width=15, command=subtraction1)
Sub1Button.grid(row=2, column=3, padx=5)

Sub2Button = Button(root, text=' Subtraction \n (1-200)', bg='green',
    width=15, command=subtraction2)
Sub2Button.grid(row=2, column=4, padx=5)

Sub3Button = Button(root, text=' Subtraction \n (1-500)', bg='green',
    width=15, command=subtraction3)
Sub3Button.grid(row=2, column=5, padx=5)

# create an output label
label4 = Label(root, text='------------', bg='beige')
label4.grid(row=3, column=4, columnspan=2, pady=10)

# start the mouse/keyboard event loop
root.mainloop()

Nice man awesome!!!, thanks for the child button coding really helped.

oh btw you made the program as when you click say addition 1-100 it brings up a question and when you answer that question correctly it exits that window. Im asking what would be the coding to make it implement another question from the same operation 9 more times but of course with other random questions so the user is intitled to answer 10 questions all up from each operation the user chooses e.g. 10 questions asked from addition 1-100, 10 questions asked from addition 1-200, 10 questions asked from addition 1-500 and same for subtraction etc...

The program is fine the way it is but im just asking how to make it ask 10 random questions besides asking one, getting it correct, then exiting out the window.

Thanks mate!

If you simplify some more, you can move the random part into the ask_player() function. Now an extra while loop takes care of 10 questions ...

# a simple math quiz game using Tkinter

from Tkinter import *
from tkSimpleDialog import askinteger  # also has askfloat, askstring
import random

def get_number(title="Integer Entry", prompt="Enter a number: "):
    return askinteger(title, prompt)

def addition1():
    """
    a helper function since command uses function names not calls
    """
    # ask_player(operator, maximum number)
    ask_player('+', 100)

def addition2():
    ask_player('+', 200)

def addition3():
    ask_player('+', 500)

def subtraction1():
    ask_player('-', 100)

def subtraction2():
    ask_player('-', 200)

def subtraction3():
    ask_player('-', 500)

def ask_player(op, max_num):
    name = enter1.get()
    # use a default name if none is given
    if not name:
        name = "Player"

    quest = 1
    wrong = 0
    while quest <= 10:
        num1 = random.randint(1, max_num)
        num2 = random.randint(1, max_num)
        eval_string = str(num1) + op + str(num2)
        answer = eval(eval_string)
        myprompt = str(quest) + ': What is ' + eval_string + ' ?'
        attempt = 1
        while True:
            myanswer = get_number(prompt=myprompt)
            if myanswer == answer:
                label4.config(text=name + ", you are correct!")
                break
            # optional, give the player 1 more attempt to get it right
            if attempt > 1:
                label4.config(text=name + ", you used up your extra attempt!")
                wrong += 1
                break
            label4.config(text=str(attempt) + ": Not correct! Try again!")
            attempt += 1
        quest += 1
    label4.config(text=name + ", out of 10 questions you had " + \
        str(wrong) + " wrong!")


# create the window and give it a title
# the root window will expand to accomodate all
root = Tk()
root.title("Main Menu - Mathematics Quiz")
root.configure(bg='beige')

# ask for the player's name
# Label and Entry
label1 = Label(root, text="Please Enter Your\n Name Below:", bg='beige')
label1.grid(row=0, column=2, pady=5)
enter1 = Entry(root, width=15, bg='green')
enter1.grid(row=1, column=2, pady=5)

# create your ops buttons
Add1Button = Button(root, text=' Addition \n (1-100)', bg='green',
    width=15, command=addition1)
Add1Button.grid(row=2, column=0, padx=5)

Add1Button = Button(root, text=' Addition \n (1-200)', bg='green',
    width=15, command=addition2)
Add1Button.grid(row=2, column=1, padx=5)

Add1Button = Button(root, text=' Addition \n (1-500)', bg='green',
    width=15, command=addition3)
Add1Button.grid(row=2, column=2, padx=5)

Sub1Button = Button(root, text=' Subtraction \n (1-100)', bg='green',
    width=15, command=subtraction1)
Sub1Button.grid(row=2, column=3, padx=5)

Sub2Button = Button(root, text=' Subtraction \n (1-200)', bg='green',
    width=15, command=subtraction2)
Sub2Button.grid(row=2, column=4, padx=5)

Sub3Button = Button(root, text=' Subtraction \n (1-500)', bg='green',
    width=15, command=subtraction3)
Sub3Button.grid(row=2, column=5, padx=5)

# create an output label
label4 = Label(root, text='------------', bg='beige')
label4.grid(row=3, column=3, columnspan=2, pady=10)

# start the mouse/keyboard event loop
root.mainloop()

I used helper functions, but you could have used lambda functions or partial functions. At this point, helper functions are much easier to understand.

If you simplify some more, you can move the random part into the ask_player() function. Now an extra while loop takes care of 10 questions ...

# a simple math quiz game using Tkinter

from Tkinter import *
from tkSimpleDialog import askinteger  # also has askfloat, askstring
import random

def get_number(title="Integer Entry", prompt="Enter a number: "):
    return askinteger(title, prompt)

def addition1():
    """
    a helper function since command uses function names not calls
    """
    # ask_player(operator, maximum number)
    ask_player('+', 100)

def addition2():
    ask_player('+', 200)

def addition3():
    ask_player('+', 500)

def subtraction1():
    ask_player('-', 100)

def subtraction2():
    ask_player('-', 200)

def subtraction3():
    ask_player('-', 500)

def ask_player(op, max_num):
    name = enter1.get()
    # use a default name if none is given
    if not name:
        name = "Player"

    quest = 1
    wrong = 0
    while quest <= 10:
        num1 = random.randint(1, max_num)
        num2 = random.randint(1, max_num)
        eval_string = str(num1) + op + str(num2)
        answer = eval(eval_string)
        myprompt = str(quest) + ': What is ' + eval_string + ' ?'
        attempt = 1
        while True:
            myanswer = get_number(prompt=myprompt)
            if myanswer == answer:
                label4.config(text=name + ", you are correct!")
                break
            # optional, give the player 1 more attempt to get it right
            if attempt > 1:
                label4.config(text=name + ", you used up your extra attempt!")
                wrong += 1
                break
            label4.config(text=str(attempt) + ": Not correct! Try again!")
            attempt += 1
        quest += 1
    label4.config(text=name + ", out of 10 questions you had " + \
        str(wrong) + " wrong!")


# create the window and give it a title
# the root window will expand to accomodate all
root = Tk()
root.title("Main Menu - Mathematics Quiz")
root.configure(bg='beige')

# ask for the player's name
# Label and Entry
label1 = Label(root, text="Please Enter Your\n Name Below:", bg='beige')
label1.grid(row=0, column=2, pady=5)
enter1 = Entry(root, width=15, bg='green')
enter1.grid(row=1, column=2, pady=5)

# create your ops buttons
Add1Button = Button(root, text=' Addition \n (1-100)', bg='green',
    width=15, command=addition1)
Add1Button.grid(row=2, column=0, padx=5)

Add1Button = Button(root, text=' Addition \n (1-200)', bg='green',
    width=15, command=addition2)
Add1Button.grid(row=2, column=1, padx=5)

Add1Button = Button(root, text=' Addition \n (1-500)', bg='green',
    width=15, command=addition3)
Add1Button.grid(row=2, column=2, padx=5)

Sub1Button = Button(root, text=' Subtraction \n (1-100)', bg='green',
    width=15, command=subtraction1)
Sub1Button.grid(row=2, column=3, padx=5)

Sub2Button = Button(root, text=' Subtraction \n (1-200)', bg='green',
    width=15, command=subtraction2)
Sub2Button.grid(row=2, column=4, padx=5)

Sub3Button = Button(root, text=' Subtraction \n (1-500)', bg='green',
    width=15, command=subtraction3)
Sub3Button.grid(row=2, column=5, padx=5)

# create an output label
label4 = Label(root, text='------------', bg='beige')
label4.grid(row=3, column=3, columnspan=2, pady=10)

# start the mouse/keyboard event loop
root.mainloop()

I used helper functions, but you could have used lambda functions or partial functions. At this point, helper functions are much easier to understand.

Excellent mate! just what i wanted :) thumbs up to you mate, thanks for all the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.