Home > Blockchain >  How do I store data from a text file to then use it within a tkinter button?
How do I store data from a text file to then use it within a tkinter button?

Time:04-13

from tkinter import *
from random import choice

text_file_list = ["question1.txt", "question2.txt", "question3.txt", "question4.txt"]

def user_interface():
    window = Tk()
    window.geometry("500x500")
    window.title("Question")
                    
    with open(choice(text_file_list), "r") as f:
            Label(window, text=f.readline()).pack()
                    
    Answer_A = Button(window, text="Answer A").pack(pady=10) 
    Answer_B = Button(window, text="Answer B").pack(pady=10)
    Answer_C = Button(window, text="Answer C").pack(pady=10)
    window.mainloop()

user_interface()

The aim of my code is to ask the user a question from a text file and then give them three buttons to chose the answer from. My code currently choses a random question and the buttons are displayed but do not have a function yet.

The correct answers to the questions are within the text file with the question itself. How can I get this answer and use it within my tkinter buttons?

CodePudding user response:

Do you mean something like this?

from tkinter import *
from random import choice

text_file_list = ["question1.txt", "question2.txt", "question3.txt", "question4.txt"]


def user_interface():
    window = Tk()
    window.geometry("500x500")
    window.title("Question")
                    
    with open(choice(text_file_list), "r") as f:
        Label(window, text=f.readline()).pack()
        correct_answer = f.readline()
                    
    answer_label = Label(window)

    def answer_callback(answer):
        if answer == correct_answer:
            answer_label["text"] = "Your answer was correct!"
        else:
            answer_label["text"] = "Your answer was wrong."

    Button(window, text="Answer A", command=lambda: answer_callback("A")).pack(pady=10) 
    Button(window, text="Answer B", command=lambda: answer_callback("B")).pack(pady=10)
    Button(window, text="Answer C", command=lambda: answer_callback("C")).pack(pady=10)
    answer_label.pack()
    window.mainloop()

user_interface()
  • Related