i am working on quiz game project i finished almost everything but i have to calc the scores for every question but i don't know how to use conditional statement with buttons like if button_selected is A then mark obtained is 1 finally the program calc all the marks and print "your total marks is 85%"
below is a part of my code (questions):
q1 = Label(win1, text="What is the main memory in computer?: ", font="Times 20", bg="white")
q1.pack()
q1.place(x=0, y=40)
button1 = Button(win1, text="A. Dynamic RAM ", font="Times 17", fg="blue",variable=radio,value=1 ,command=selection)# true
button1.place(x=0, y=80)
button2 = Button(win1, text=" B. Static RAM ", font="Times 17", variable=radio,value=0 ,fg="blue", command=selection)
button2.place(x=0, y=120)
button3 = Button(win1, text=" C. ROM ", font="Times 17", fg="blue",variable=radio,value=1 , command=selection)
button3.place(x=0, y=160)
button4 = Button(win1, text=" D. Register", font="Times 17", fg="blue",variable=radio,value=1 ,command=selection)
button4.place(x=0, y=200)
CodePudding user response:
There are no attributes like variable
and value
for a Button
in Tkinter. Just pass the option chosen as an argument with the function selection
with each button's command (for that you can use lambda
.)
In the function selection
, check for correct answers and update the score.
from tkinter import *
win1 = Tk()
win1.geometry("600x500")
score=0
def selection(optionChose):
global score
if optionChose == 'A':
score =1
else:
score =0 #can also do negative marking for wrong
print(score)
q1 = Label(win1, text="What is the main memory in computer?: ", font="Times 20", bg="white")
q1.pack()
q1.place(x=0, y=40)
button1 = Button(win1, text="A. Dynamic RAM ", font="Times 17", fg="blue" ,command=lambda:selection('A'))# true
button1.place(x=0, y=80)
button2 = Button(win1, text=" B. Static RAM ", font="Times 17",fg="blue", command=lambda:selection('B'))
button2.place(x=0, y=120)
button3 = Button(win1, text=" C. ROM ", font="Times 17", fg="blue", command=lambda:selection('C'))
button3.place(x=0, y=160)
button4 = Button(win1, text=" D. Register", font="Times 17", fg="blue",command=lambda:selection('D'))
button4.place(x=0, y=200)
win1.mainloop()
For building a better version using Radiobuttons
as options instead of Buttons
, refer to MCQ Quiz Game using Tkinter (JSON data
will be used to extract the question & answers from.)
CodePudding user response:
The usual way to do this is to pass an argument from the button to the callback function. One way to do this is using a lambda function:
from tkinter import *
win1 = Tk()
q1 = Label(win1, text="What is the main memory in computer?: ")
q1.pack()
def selection(button):
print(button)
button1 = Button(win1, text="A. Dynamic RAM ", command=lambda:selection('A'))
button1.pack() # Parameter passed to callback function ---^
button2 = Button(win1, text=" B. Static RAM ", command=lambda:selection('B'))
button2.pack() # Parameter passed to callback function ---^
win1.mainloop()