0

I am trying to create a simple python program with one thread handling UI and another “Background stuff”. I'd like to run a function when the user tries to exit my application a dialogue choice appears.

When I run the following code the function “on_closing()” runs automatically. As I understand I have to pass the function name only in the protocol function but I need a couple of arguments.

class MainWindow:

    def __init__(self, master):

        master.resizable(0, 0)
        master.protocol("WM_DELETE_WINDOW", self.on_closing(master))
        do_stuff('...')

    def on_closing(self, master):
        do_stuff('...')
        self.Destroy(master)

def call_window_manager(title):
    do_stuff(title)
    root = Tk()
    mw = MainWindow(root)
    root.mainloop()


def call_tools(title, mainwindow, master):
    do_stuff(title)


if __name__ == '__main__':

    do_stuff('main line')

    p1 = mp.Process(target=call_window_manager, args=('Window Manager Thread',))
    p2 = mp.Process(target=call_tools, args=('Tools Thread',))

    p1.start()
    p2.start()
    p1.join()
    p2.join()

How do I pass arguments then? Am I approaching this with the wrong way?

Ps: what’s the best way to terminate the other thread at the same time?

1 Answer 1

3

You can pass arguments to protocol's callback function using lambda. As in replace:

master.protocol("WM_DELETE_WINDOW", self.on_closing(master))

with:

master.protocol("WM_DELETE_WINDOW", lambda arg=master: self.onclosing(arg))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! This is exactly what I needed.
master iteself is not some variable that will change over time so there is no reason to do arg=master. Simply master.protocol("WM_DELETE_WINDOW", lambda: self.on_closing(master)) will work fine here. On that note it is likely to be better to just do master.protocol("WM_DELETE_WINDOW", self.on_closing) and have the on_closing method do self.master.destroy().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.