Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- from pyforms.basewidget import BaseWidget
- from pyforms.controls import ControlText, ControlButton, ControlLabel
- class QuestionsFormApp(BaseWidget):
- def __init__(self):
- super().__init__('Questions Form')
- self._questions = [] # This will store questions from the CSV
- self._dynamic_controls = []
- csv_file_path = 'questions.csv'
- # Load questions from the CSV file
- self.load_questions_from_csv(csv_file_path)
- # Dynamically create controls based on the number of questions
- for idx, question in enumerate(self._questions):
- # Create a label for each question
- label = ControlLabel(question)
- # Create a text field for the answer
- answer_field = ControlText(f'Answer {idx + 1}')
- # Append them to the list of dynamic controls (used for submitting answers)
- self._dynamic_controls.append(answer_field)
- # Add the controls to the form
- setattr(self, f'label_{idx}', label)
- setattr(self, f'answer_{idx}', answer_field)
- # Add a submit button
- self._submit_btn = ControlButton('Submit')
- self._submit_btn.value = self.__on_submit_click
- # Interleave question labels and answer fields using zip
- form_elements = [elem for pair in zip([f'label_{idx}' for idx in range(len(self._questions))],
- [f'answer_{idx}' for idx in range(len(self._questions))])
- for elem in pair] + ['_submit_btn']
- # Assign the formset
- self.formset = form_elements
- def load_questions_from_csv(self, csv_file):
- """Load questions from a CSV file."""
- try:
- with open(csv_file, 'r') as file:
- reader = csv.DictReader(file)
- for row in reader:
- self._questions.append(row['question'])
- except FileNotFoundError:
- print(f"Error: File {csv_file} not found.")
- except KeyError:
- print("Error: CSV file does not contain 'question' column.")
- def __on_submit_click(self):
- """Handle the Submit button click."""
- answers = {}
- for idx, control in enumerate(self._dynamic_controls):
- answers[self._questions[idx]] = control.value
- print("Answers submitted:", answers)
- self.show_message("Form Submitted", "Your answers have been submitted.")
- if __name__ == '__main__':
- from pyforms import start_app
- start_app(QuestionsFormApp, geometry=(200, 200, 500, 400))
Advertisement
Add Comment
Please, Sign In to add comment