I am writing a program for passing testing in Python, but I can’t think out how to work with the GUI correctly. I have to close the window every time to switch to the next question. How best to cope with the task? Surely I am missing a simple and concise solution for no experience.

from random import shuffle from tkinter import * def count1(event): global ans1, answers, score if ans1 == answers[0]: score += 1 def count2(event): global ans1, answers, score if ans1 == answers[1]: score += 1 def count3(event): global ans1, answers, score if ans1 == answers[0]: score += 1 score = 0 tests = open('input.txt', 'r', encoding='utf-8') for i in range(0, 3): question = tests.readline() ans1 = tests.readline().strip() ans2 = tests.readline().strip() ans3 = tests.readline().strip() answers = [ans1, ans2, ans3] shuffle(answers) print(question) shuffle(answers) print(*answers, sep='\n') root = Tk() lab = Label(root, text=question, font="Arial 18") lab.pack() answ1 = Button(root) answ1['text'] = answers[0] answ1.bind('<Button-1>', count1) answ1.pack() answ2 = Button(root) answ2['text'] = answers[1] answ2.bind('<Button-1>', count2) answ2.pack() answ3 = Button(root) answ3['text'] = answers[2] answ3.bind('<Button-1>', count3) answ3.pack() root.mainloop() print(score) 
  • one
    I advise you to try PyQt5. A huge number of examples and information. If you know the C ++ syntax, then Qt has divine docks. - Philip Bondarev

1 answer 1

You need not to drive the program into a cycle, and certainly not to create the main window each time, but:

1) Or hide widgets (perhaps the best way) using the pack_forget method For example:

 from tkinter import * def hide_me(event): event.widget.pack_forget() root = Tk() btn=Button(root, text="Click") btn.bind('<Button-1>', hide_me) btn.pack() btn2=Button(root, text="Click too") btn2.bind('<Button-1>', hide_me) btn2.pack() root.mainloop() 

More details here .

2) Either delete them via the destroy method. Only unlike pack_forget you can’t get them back later.

3) Or create child windows via Toplevel() . For example:

 import tkinter as tk class MainWindow(tk.Frame): counter = 0 def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.button = tk.Button(self, text="Create new window", command=self.create_window) self.button.pack(side="top") def create_window(self): self.counter += 1 t = tk.Toplevel(self) t.wm_title("Window #%s" % self.counter) l = tk.Label(t, text="This is window #%s" % self.counter) l.pack(side="top", fill="both", expand=True, padx=100, pady=100) if __name__ == "__main__": root = tk.Tk() main = MainWindow(root) main.pack(side="top", fill="both", expand=True) root.mainloop() 

More details here .