0
votes

I'm using tkinter for the first time and I've created a window that has a listbox with values that the user can select. These values are passed into a function, and any console output is shown in a text box in the window.

Here's my code:

class Display(tk.Frame):
    def __init__(self,parent=0):
       tk.Frame.__init__(self,parent)

       # code here that creates a bunch of widgets

       sys.stdout = self

       # code here that packs widgets into frame

    def onSubmit(self):
        self.years = list()
        self.selection = self.lstbox.curselection()
        for i in self.selection:
            entry = self.lstbox.get(i)
            self.years.append(int(entry))
        batch_process(self.years)

    def write(self, txt):
        self.output.insert(tk.END,str(txt))
        self.output.see(tk.END)
        self.update_idletasks()  


class MainW(tk.Tk):
    def __init__(self, parent):
        tk.Tk.__init__(self ,parent)
        self.parent = parent
        self.display = Display(self)
        self.display.pack()
        self.title('Test')

        self.protocol('WM_DELETE_WINDOW', self.close_window)

    def close_window(self):
        if messagebox.askokcancel('Exit', 'Are you sure you want to close?'):
            self.destroy()

if __name__=='__main__':
    window = MainW(None)
    window.mainloop()

The window works fine - listbox successfully passes values into the function and output is shown in the textbox.

However, when I click "X" and close the window, the console shows that the script is still running for some reason. I then have to completely close Spyder in order to run the script again. What's the issue? My understanding is that destroy() would terminate the mainloop.

EDIT: Had someone else run the script and got the following error:

Exception ignored in: <__main__.Display object .!display> 
AttributeError: 'Display' object has no attribute 'flush'
1
When I run your code from the command line (after adding code necessary to make it run), it behaves exactly as I would expect. If I click "ok" in the messagebox, the script exits. - Bryan Oakley
Try running the code outside your IDE, as in, directly through python. - nosklo
Why do I have to do that? I'd like to avoid that if possible. I had someone else run the script and got this error when hitting "X" and ok: "Exception ignored in: <__main__.Display object .!display> AttributeError: 'Display' object has no attribute 'flush'". - jerbear
I got it... even though I don't fully understand it. I had to add a "flush" function to my Display class. def flush(self): pass. - jerbear

1 Answers

0
votes

I got it... even though I don't fully understand it. I had to add a "flush" function to my Display class.

def flush(self): 
    pass