[Python] After using __str__, Tkinter still shows repl <xxx object at location xxxxxxxxx>

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm learning Python through the course and the assignment was to write an OOP quiz application.

    Old prompt under spoilers.

    When I run the code, I expect that after choosing the length of the quiz, it will close the current window and open the quiz window with the text of the question, but it shows repr.

    Main window where you choose length the problem

    The problem is in the Ui class somewhere, because when I tested other modules, it worked as it should (printing answers in the terminal), but when it gets to the Ui stage it breaks.

    This is: data. py, works

    import requests
    import json

    with open("quizztype.txt", "r") as qt:
    value = qt.readline()

    parameters = {
    "amount": value,
    "type": "boolean",
    }

    response = requests.get("https://opentdb.com/api.php",
    params=parameters)
    # response.raise_for_status()

    question_data = json.loads(response.text)


    This is: main.py, and it works

    from question_model import Question
    from data import question_data
    from quiz_brain import QuizBrain
    from ui import Ui
    import html

    question_bank = []
    for question in question_data['results']:
    question_text = html.unescape(question['question'])
    question_answer = question['correct_answer']
    new_question = Question(question_text, question_answer)
    question_bank.append(str(new_question))

    quiz = QuizBrain(question_bank)
    ui = Ui(QuizBrain)


    This is: question_model.py, and it works

    class Question:

    def __init__(self, q_text: str, q_answer: str):
    self.text = q_text
    self.answer = q_answer

    def __str__(self) -> str:
    return f"Q.{self.text}: {self.answer}"


    This is: quiz_brain.py, and it works, but it might be the problem.

    from question_model import Question
    from data import question_data
    from ui import Ui
    import html

    class QuizBrain:

    def __init__(self, q_list: list):
    self.question_number = 0
    self.score = 0
    self.question_list = q_list
    self.current_question = None
    self.what_to_return = str


    def __str__(self) -> str:
    self.what_to_return = str(f"Q.{self.question_number}: {self.current_question}")
    return self.what_to_return


    def still_has_questions(self):
    return self.question_number < len(self.question_list)

    """This could be a problematic part"""
    def next_question(self):
    self.current_question = str(self.question_list[self.question_number])
    self.question_number += 1
    self.what_to_return = str(f"Q.{str(self.question_number)}: {str(self.current_question)}")
    return self.what_to_return

    # self.check_answer(user_answer)

    def check_answer(self, user_answer):
    correct_answer = self.current_question
    if user_answer.lower() == correct_answer.lower():
    self.score += 1
    print("You got it right!")
    else:
    print("That's wrong.")

    print(f"Your current score is: {self.score}/{self.question_number}")
    print("\n")



    And last is the Tkinter GUI.

    I think that the way I did it is probably stupid, but I don't know better and didn't find better. And I think that somewhere here is the problem.

    import tkinter as tk

    score = 0
    THEME_COLOR = "#375362"

    class Ui():

    def __init__(self, quiz_brain) -> None:

    self.window = tk.Tk()
    self.quiz = quiz_brain
    self.window.minsize(width=300, height=300)
    self.window.config(padx=10, pady=10)
    self.window.title('Quizz Game')

    self.label_10_questions = tk.Label(text='Quizz that contains 10 questions')
    self.label_10_questions.place(x=50,y=30)
    self.questions_button_10 = tk.Button(text='select',command= self.game_ui_10 )
    self.questions_button_10.place(x=115, y= 75)
    self.highscore_10 = tk.Label(text= f'highscore {score}')
    self.highscore_10.place(x=50, y=50)
    self.button_exit = tk.Button(text= 'Exit', command=self.window.destroy)
    self.button_exit.place(x=250, y= 250)
    self.window.mainloop()

    """potential problem and anywhere it's used"""
    def next_question_correct(self):
    q_text = str(self.quiz.next_question)
    canvas.itemconfig(str(question_text), text=str(q_text))


    def game_ui_10(self,):
    global canvas
    global question_text
    self.window.destroy()
    with open("quizztype.txt", "w") as qt:
    qt.write("10")

    window = tk.Tk()
    window.minsize(width=500, height=400)
    window.config(padx=10, pady=10, bg=THEME_COLOR)
    window.title('Quizz Game')

    canvas = tk.Canvas(width=450, height=150, bg='white')
    canvas.place(x=15, y=60)
    question_text = canvas.create_text(200,75, text= "x", fill=THEME_COLOR, font=("Arial",20, "italic"), width=400)
    true_image = tk.PhotoImage(file="images/true.png")
    false_image = tk.PhotoImage(file="images/false.png")
    true_button = tk.Button(image= true_image, highlightthickness=0, command=self.next_question_correct)
    true_button.place(x= 15, y= 260)
    false_button = tk.Button(image=false_image, highlightthickness=0, command=self.next_question_correct)
    false_button.place(x=350, y= 260)

    score_label = tk.Label(text=f"Score {0}/{0}", bg= THEME_COLOR, fg="white", font=("Arial",15, "normal"))
    score_label.place(x= 350, y= 10)

    str(self.next_question_correct())
    window.mainloop()
    ui = Ui(self.quiz)



    Because I'm learning, I just browsed the Internet and found that __repr__ or __str__ can help with converting <xxxx object at location xxxxx> to normal text, so that is what I used. I don't know what else I could do.

    Continue reading...

Compartilhe esta Página