Reputation: 75
I am currently learning python in school and its winter break so I really wanted to learn some GUI for python so I started learning tkinter. Currently I am trying to make it so everytime user gets the answer correct it will move on to the next line in the file but I have no idea how to do it, I have tried all day doing it just to make sure I wasnt missing anything but couldnt find what I was looking for, if anyone could please help me I would be so happy.
def correctquestion(e):
correct.configure(text="Correct")
def incorrectquestion(e):
correct.configure(text="Incorrect")
def lines(e):
file_name = open("state_capitals.txt", "r")
line = file_name.readline().strip().split(",")
return line
def nextquestion(e):
line = lines(e)
data = answerBox.get()
if line[1] == data:
correctquestion(e)
questionBox.configure(text=line[0])
else:
incorrectquestion(e)
questionBox.configure(text=line[0])
root = Tk()
frame = Frame(root)
Grid.rowconfigure(root, 0, weight=0)
Grid.columnconfigure(root, 0, weight=1)
frame.grid(row=0, column=0)
root.geometry('{}x{}'.format(500, 500))
root.resizable(width=False, height=False)
line = lines(root)
AnswerButton = Button(root, text="Submit")
AnswerButton.grid(row=3, sticky=W, padx=(80, 10))
AnswerButton.bind("<Button-1>", nextquestion)
questionBox = Label(root, text=line[0], bg="red", fg="white")
questionBox.config(font=("Courier", 30))
questionBox.grid(row=0, sticky=W + E, ipady=30)
root.mainloop()
Upvotes: 0
Views: 1655
Reputation: 142651
Better read all file and keep all lines in memory - it will be easier.
Example code - not tested - I don't have file with questions :)
import tkinter as tk
# --- functions --- (lower_case names)
def read_file():
file_ = open("state_capitals.txt")
# create list of lines
lines = file_.read().split('\n')
# split every line in columns
lines = [l.split(',') for l in lines]
return lines
def next_question():
global current_question # inform function to use global variable instead local because we will assign new value
data = answer_Box.get()
if all_lines[current_question][1] == data:
correct.configure(text="Correct")
current_question += 1
if current_question < len(all_lines):
question_box.configure(text=all_lines[current_question][0])
else:
question_box.configure(text="THE END")
else:
correct.configure(text="Incorrect")
# --- main --- (lower_case names)
all_lines = read_file()
current_question = 0 # create global variable
root = tk.Tk()
root.geometry('500x500')
root.resizable(width=False, height=False)
root.rowconfigure(0, weight=0)
root.columnconfigure(0, weight=1)
answer_button = tk.Button(root, text="Submit", command=next_question)
answer_button.grid(row=3, sticky='w', padx=(80, 10))
question_box = tk.Label(root, text=all_lines[current_question][0],
bg="red", fg="white", font=("Courier", 30))
question_box.grid(row=0, sticky='we', ipady=30)
correct = tk.Label(root)
correct.grid(row=1, sticky='we', ipady=30)
root.mainloop()
BTW: PEP 8 -- Style Guide for Python Code
Upvotes: 2