简体   繁体   中英

Python 3 and Tkinter: Displaying Questions and Varying Answer Sets by OOP in Survey Form

I am creating a survey form with questions and varying sets of possible answers using Python 3 and Tkinter.

The following lines of codes are not displaying my survey questions and their answer sets. Instead, they produce an error < main .QuestionSet object at 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()

To customize the string representation of a class, you can override the __str__ method of your class. It should return a string. In your case you could do:

class QuestionSet:
    def __init__(self, *args, **kwargs):
        self.question = questionSet

    def __str__(self):
        return self.question[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM