После использования __str__ Tkinter по -прежнему показывает Repl Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 После использования __str__ Tkinter по -прежнему показывает Repl

Сообщение Anonymous »

Я изучаю Python через курс, и задача заключалась в том, чтобы написать приложение OOP -викторины. < /p>

Старая подсказка под спойлерами. Длина
Проблема < /p>
Проблема в классе пользовательского интерфейса где -то, потому что, когда я тестировал другие модули, она работала, как и должна (печатая ответы в терминале), но когда он попадает на стадию пользовательского интерфейса, он ломается. < /p>
Это: данные. py, работает < /p>

Код: Выделить всё

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)
< /code>
Это: main.py, и он работает < /p>
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)
< /code>
Это: Вопрос_model.py, и он работает < /p>
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}"
< /code>
Это: quiz_brain.py, и это работает, но это может быть проблемой.  < /p>
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")

< /code>
И последнее - это графический интерфейс tkinter.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 __ может помочь с преобразованием в нормальный текст, так что я использовал. Я не знаю, что еще я мог бы сделать.

Подробнее здесь: https://stackoverflow.com/questions/767 ... -xxxxxxxxx
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»