python-3.x 使用__str__后,Tkinter仍然显示repl< xxx object at location xxxxxxxxx>

noj0wjuj  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(68)

我正在通过课程学习Python,作业是编写一个OOP测验应用程序。
我想做一个Tkinter图形用户界面,从主窗口中选择三个长度之一,(10,25 50个问题)和每个关闭的主窗口记录了一些问题,并将其写入txt的数据读取,然后你就完成了测试。但是它显示了(当它在终端打印时)当它不应该的时候。我浏览了一下,找到了__str__,它还可以。然后我做了Tkinter GUI,但是问题又回来了,__str__没有帮助,我不知道该怎么办了。
旧提示下剧透。
当我运行代码时,我希望在选择测验的长度后,它会关闭当前窗口并打开带有问题文本的测验窗口,但它显示repr。
Main window where you choose lengththe problem
问题出在Ui类的某个地方,因为当我测试其他模块时,它正常工作(在终端中打印答案),但当它到达Ui阶段时,它就崩溃了。
这是: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)

字符串
这是:main.py,它可以工作

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)


这是:question_model.py,它可以工作

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}"


这是:quiz_brain.py,它可以工作,但它可能是问题所在。

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")


最后是Tkinter GUI。
我想我做的方式可能很愚蠢,但我不知道更好的,也没有找到更好的。我想这里的某个地方是问题所在。

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)


因为我在学习,我只是浏览了一下互联网,发现__repr____str__可以帮助将<xxxx object at location xxxxx>转换为普通文本,所以我就用了。我不知道我还能做什么。

fjnneemd

fjnneemd1#

我不确定这是否解决了str的问题,但不是传递类本身,而是创建QuizBrain的示例并将其传递给Ui类。
main.py:

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

字符串
对此:

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

相关问题