Creating a tkinter quick multiplication game using recursion - python-3.x

I'm trying to create a game that generates 2 random numbers and then the user has to type the correct answer of the product of it, then 1 point is gained. I'm trying to get it to stop once it's been done 10 times however I can't seem to get it to end. I tried using a loop rather than recursion but I also got stuck on that.
import tkinter as tk
from tkinter import *
import random
numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
qm_score = 0
global recursion_count
recursion_count = 0
quickmulti_page = tk.Tk()
quickmulti_page.title =("Quick multiplication")
quickmulti_page.config(background="SlateGray1")
quickmulti_page.geometry("300x200")
def endgame():
print("Youre done")
print(qm_score)
def multiplication():
def multi_answer(event):
recursion_count = recursion_count + 1
if recursion_count == 10:
if user_answer == answer:
qm_score = qm_score + 1
endgame()
else:
endgame()
elif recursioncount > 3:
multiplication()
else:
endgame()
num1 = random.choice(numbers)
num2 = random.choice(numbers)
answer = num1 * num2
qlabel = Label(quickmulti_page, text=(num1,"x", num2), font=100, width=20, height=3).place(x=50,y=40)
user_answer = Entry(quickmulti_page,width=30)
user_answer.place(x=50, y=120)
user_answer.bind('<Return>', multi_answer)

Related

Property method in python not returning correct value

I am trying to solve the question in which I am asked to use property method to count the number of times the circles are created . Below is the code for the same.
import os
import sys
#Add Circle class implementation below
class Circle:
counter = 0
def __init__(self,radius):
self.radius = radius
Circle.counter = Circle.counter + 1
def area(self):
return self.radius*self.radius*3.14
def counters():
print(Circle.counter)
no_of_circles = property(counter)
if __name__ == "__main__":
res_lst = list()
lst = list(map(lambda x: float(x.strip()), input().split(',')))
for radius in lst:
res_lst.append(Circle(radius).area())
print(str(res_lst), str(Circle.no_of_circles))
The above code gives correct output for the area but counter should be 3 and instead I am getting below output . Below is the output for input = 1,2,3
[3.14, 12.56, 28.26] <property object at 0x0000024AB3234D60>
I have tried everything but no luck. In the main section of the code no_of_circles is called as Circle.no_of_circles which suggests me that it will use property method of python. But the output is wrong. Please help me find where I am going wrong.
Here is a simple working example using the property function.
Note: It is always a good practice to make an instance of a class(once) and then uses the instance all over your code. Also better to use self.counter instead of Cirlcle.counter. self is Circle.
#Add Circle class implementation below
class Circle:
def __init__(self,value=0):
self._counter = value
def area(self, radius):
return radius*radius*3.14
def add_counter(self, value):
print('add counter')
self._counter += 1
def get_counter(self):
print('get counter')
return self._counter
no_of_circles = property(get_counter, add_counter)
if __name__ == "__main__":
circle = Circle()
area = []
for idx in range(5):
area.append(circle.area(idx))
circle.add_counter(1)
print("number of calls: ", circle.no_of_circles)
print('area:', area)
output(note how get and add counter are called):
add counter
add counter
add counter
add counter
add counter
get counter
number of calls: 5
area: [0.0, 3.14, 12.56, 28.26, 50.24]
str(Circle.no_of_circles) here you're calling the property of a class not an instance of that class i.e a Circle object; the following will work :-
class Circle:
counter = 0
def __init__(self,radius):
self.radius = radius
Circle.counter = Circle.counter + 1
def area(self):
return self.radius*self.radius*3.14
def counters():
print(Circle.counter)
no_of_circles = property(counter)
if __name__ == "__main__":
lst = list(map(lambda x: float(x.strip()), input("Enter radius : ").split(',')))
cir_lst = [Circle(_) for _ in lst]
res_lst = [__.area() for __ in cir_lst]
print(res_lst, cir_lst[-1].counter)

Tic-tac-toe using python tkinter

Tic-tac-toe game using python tkinter is not working correctly.
Tic-tac-toe structure is correct. I just want to change the click event.
Only button9 output shown when click to any button
Every time I click any button this output is shown
from tkinter import *
bclick = True
tk = Tk()
tk.title("Tic Tac toe")
tk.geometry("300x400")
n = 9
btns = []
def ttt(button):
global bclick
print(button)
if button["text"] == "" and bclick == True:
print("if")
button.config(text="X")
bclick = False
elif button["text"] == "" and bclick == False:
print("else")
button["text"] = "0"
bclick = True
for i in range(9):
btns.append(Button(font=('Times 20 bold'), bg='white', fg='black', height=2, width=4))
row = 1
column = 0
index = 1
print(btns)
buttons = StringVar()
for i in btns:
i.grid(row=row, column=column)
i.config(command=lambda: ttt(i))
print(i, i["command"])
column += 1
if index % 3 == 0:
row += 1
column = 0
index += 1
tk.mainloop()
Common misstake. The lambda function is using the last value assigned to i so every lambda will use i=.!button9. change the lambda function to:
i.config(command=lambda current_button=i: ttt(current_button))
which will make lambda use the value of i when the lambda was created.

how to get the results of two different functions

hello i have a code that looks like this
from multiprocessing import Process
from tkinter.messagebox import *
from time import sleep
def timerclose():
sumtimer = 0
while sumtimer <= 10 :
sleep(0.1)
sumtimer = sumtimer + 0.1
print("sumtimer",sumtimer)
return sumtimer
def conout():
confirmation = askokcancel ("confirmation","are you sure ?")
return confirmation
if __name__=='__main__':
p1 = Process(target=timerclose)
p1.start()
p2 = Process(target=conout)
p2.start()
I wanted to create an askokcancel message box with a timeout. i want the messagebox to popout to ask the user if we wants to exit or not and simultaneously starts a counter. after 10 seconds if the user does not press anything (ok or cancel) i would get the return value from the timerclose ignore the conout function and continue with the rest of the programm.
i solve it with one process and a shared value
def conout(n):
n.value = int(0)
confirmation = askokcancel ("confirmation","Σε 10 sec κλείνω Οκ ?")
if confirmation == True :
n.value = int(1)
else:
n.value = int(2)
if __name__=="__main__":
p2 = Process(target=conout, args=(num,))
p2.start()
timerls = 0
while timerls <= 10:
sleep(0.25)
timerls += 0.25
print("timerls",timerls)
if num.value == 1 :
print ("end true",num.value)
break
elif num.value == 2:
print ("end false", num.value)
break
else:
print ("end0", num.value)

What is wrong with my elif statement? Invalid Syntax

if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
from tkinter import *
def mhello():
mtext = ment.get()
mLabel2 = Label(test, text=mtext).pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+10')
test.title('Test')
mlabel = Label(test, text='Time to guess').pack()
mbutton = Button(test, text='Click', command = mhello).pack()
mEntry = Entry(test, textvariable=ment).pack()
test.mainloop()
from tkinter import *
def mhello():
my_word = 'HELLO'
mtext = ment.get()
if my_word == mtext:
mLabel2 = Label(test, text='Correct').pack()
else:
mLabel2 = Label(test, text='Incorrect').pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+300')
test.title('Test')
def label_1():
label_1 = Label(test, text='Hello. Welcome to my game.').pack()
def label_2():
label_2 = Label(test, text='What word am I thinking of?').pack()
button_1 = Button(test, text='Click', command = mhello).pack()
entry_1 = Entry(test, textvariable=ment).pack()
label_1()
test.after(5000, label_2)
test.mainloop()
from tkinter import *
from random import shuffle
game = Tk()
game.geometry('200x200')
game.grid()
game.title("My Game")
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def board_1():
board1 = []
k = 0
for i in range(3):
for j in range(3):
board1.append(Label(game, text = board[k]))
board1[k].grid(row = i, column = j)
k +=1
def board_2():
shuffle(board)
board2 = []
k = 0
for i in range(3):
for j in range(3):
board2.append(Label(game, text = board[k]))
board2[k].grid(row = i, column = j)
k +=1
board_1()
game.after(5000, board_2)
game.mainloop()
#2nd Option
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
The bit that has the Syntax Error is the 1st elif statement (2nd Option). Ignore all the code prior to this if necessary (it is there for context). Whenever I run the code it says that there is a syntax error and just positions the typing line (I don't know what it's called) at the end of the word elif.
This is a simple fix, with if else statements you need to have a closing ELSE and in this case there is not so when your program runs it sees that theres a lonely if without its else :)
if option == "1":
elif option == "2":
else:
'do something else in the program if any other value was recieved'
also a switch statement can be used here so it does not keep checking each condition and just goes straight to the correct case :D
The problem is that your block is separated from the first if-statement, where it actually belongs to. As it is, it follows the game.mainloop() statement, and adds an unexpected indentation. Try to rearrange your code like so:
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
[ Rest of the code ]

Python quiz, using tkinter

from tkinter import *
import tkinter as tk
q = 0
s = -1
count = 0
correct = 0
incorrect = 0
question = ["Is this a quiz","Are you sure","Dont be","see its not a quiz"]
answer = ["yes","yes","ok","ok"]
answer_cap = ["Yes","Yes","Ok","Ok"]
root = Tk()
name = tk.Label(root,text = "GUI Quiz")
name.pack()
label = tk.Label(root,text = question[0])
label.pack()
entry = tk.Entry(root)
entry.pack()
def out():
global q,correct,incorrect,s,count
count = count + 1
ans = entry.get()
print (ans)
print (question[q])
print (answer[q])
if count < 4:
if answer[q] or answer_cap[q] == ans :
q = q + 1
entry.delete(0, END)
correct = correct + 1
label.config(text = question[q])
else:
q = q + 1
entry.delete(0, END)
incorrect = incorrect + 1
label.config(text = question[q])
else:
entry.delete(0, END)
label.config(text = "Correct: "+str(correct) + " Incorrect: "+str(incorrect))
def stop():
global q,correct,incorrect
q = 0
correct = 0
incorrect = 0
entry.delete(0, END)
label.config(text = question[0])
button = tk.Button(root,text = "Submit",command = out)
button.pack()
button_two = tk.Button(root,text = "Restart",command = stop)
button_two.pack()
root.mainloop()
nothing actually wrong with the code its just how I'm doing it. When I run module it will ask my four questions and I will give the answer, but no matter what I put it will say I got 3 correct and none wrong. Am I missing something obvious or is it how I layed out the code.
The first part of your out function should not have 'count = count + 1' because this adds one to you score regardless of weather you were right or wrong; relocate the commented code.
def out():
global q,correct,incorrect,s,count
#count = count + 1
ans = entry.get()
print (ans)
print (question[q])
print (answer[q])

Resources