Python 3 和 Tkinter:以调查形式通过 OOP 显示问题和不同的答案集



我正在使用Python 3和Tkinter创建一个包含问题和各种可能答案的调查表。

以下代码行未显示我的调查问题及其答案集。相反,它们会产生错误<<strong>main。问题集对象在0x000000B3CB464400>:

from tkinter import *
root = Tk()
question = " "
def button_press(btn):
    global question
    question = btn
    questionStatement.set(question)
# Create Class for sets of questions and their possible answers
class QuestionSet:
    def __init__(self, questionSet):
        self.question = questionSet           
        # to display answer options with radio button
        def answer_options():
            for counter in range(len(question)-1):
                radioButton = RADIOBUTTON(text=question[counter])
                radioButton.grid(row=2, column=counter)
        answer_options()
# List of questions and their possible answers
q1 = QuestionSet(["Assessment 1", "Yes", "No"])
q2 = QuestionSet(["Assessment 2", "Yes", "No", "Maybe"])
q3 = QuestionSet(["Assessment 3", "Agree", "Disagree"])
q4 = QuestionSet(["Assessment 4", "Yes", "No"])
# Display Questions
questionStatement = StringVar()
questionStatement.set(q1)
questionField = Label(textvariable=questionStatement)
questionField.grid(columnspan=10, sticky="E")
# button to select questions to be answered
button1 = Button(text="1", command=lambda: button_press(q1))
button2 = Button(text="2", command=lambda: button_press(q2))
button3 = Button(text="3", command=lambda: button_press(q3))
button4 = Button(text="4", command=lambda: button_press(q4))
button1.grid(row=2, column=0)
button2.grid(row=2, column=1)
button3.grid(row=2, column=2)
button4.grid(row=2, column=3)
root.mainloop()

若要自定义类的字符串表示形式,可以重写类的 __str__ 方法。它应该返回一个字符串。在您的情况下,您可以执行以下操作:

class QuestionSet:
    def __init__(self, *args, **kwargs):
        self.question = questionSet
    def __str__(self):
        return self.question[0]

最新更新