Home > Back-end >  tkinter: how to remove from canvas placed widget in OOP
tkinter: how to remove from canvas placed widget in OOP

Time:09-28

I am building a small App with Tkinter, which shows questions and gets Radiobutton or Entry responses, with a 'Next' button that proceeds to a new question shown in the same window.

Everything works well, except that the Entry box & self.opts.value-s never disappear from the canvas, but overlay instead:

this is how it looks

I've tried to google it, but the solutions are usually for the reset within the same function. How can I store a widget in one function (display_input_box, make_radio_buttons) to be able to call it further from another (next_btn) function and then place_forger or something?

class App():

  def __init__(..):
        self.window = Tk()
        self.canvas = Canvas(width, height, ...)
  ...
  
  def gui_buttons(self):
        ...
        next_button = Button(self.window, text="Next", 
                             command=self.next_btn,...)
        next_button.place(x,y)
        ...

  def display_input_box(self):
        self.user_answer.set(None)
        entry = Entry(self.window, textvariable = self.user_answer) 
        self.entry.place(x,y)

  def make_radio_buttons(self):
        choice_list = []
        ...
        while len(choice_list) <= len(self.options):
            radio_btn = Radiobutton(self.window, text="", variable=self.user_answer,...)
            choice_list.append(radio_btn)
            radio_btn.place(x,y).  
        return choice_list
    
  def display_options(self):
        ...
        val=0
        self.user_answer.set(None)
        self.opts = self.make_radio_buttons()
        for option in self.options:
            self.opts[val]['text'] = option
            self.opts[val]['value'] = option
            val  = 1

   def next_btn(self): 
        self.responses.append(self.user_answer.get())
        if self.has_more_questions():
            # display next question text
            self.display_question()
            # and its options
            if ...:
                self.display_options()
            else:
            # or entry box
                self.display_input_box()
        else:
            # if no more questions
            self.display_result()

CodePudding user response:

You could create some Frames to hold your widgets for each one of the questions you'll be dealing with, and when you pass for the next one, you can hide the whole frame and its widgets using frame.pack_forget() or frame.grid_forget() (assuming you'll use them again some time later on your app) or frame.destroy().

Also a good tip would be to create a class for each of those frames.

  • Related