Brōtsyorfuzthrāx
Brōtsyorfuzthrāx

Reputation: 4749

Tkinter maximize/restore/resize differentiation

I know in Tkinter that the "<Configure>" event handles size changes in a window. However, I need to distinguish between when a user hits the maximize button, the restore button and when the user is resizing the window (instead of all three at once). Any ideas on how to do this? Is there a standard way? For instance, when a user hits maximize, I want to execute my code to maximize. When the user hits restore, I want to execute different code to restore. When the user drags to resize (or uses the keyboard shortcut to do so) I want it to execute different code altogether.

Upvotes: 1

Views: 2289

Answers (1)

atlasologist
atlasologist

Reputation: 3964

I can't think of a built-in way to track these events, but you could use the state() method on your root window to track changes. You can check the returned values of state(), specifically normal and zoomed (looks like Windows and OSX only), and call your own methods to handle the resize type based off those values. Here's a example to clarify:

class App(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        # initialize the new_state
        self.new_state = 'normal'

        self.parent.bind('<Configure>', self._resize_handler)

    def _resize_handler(self, event):
        self.old_state = self.new_state # assign the old state value
        self.new_state = self.parent.state() # get the new state value

        if self.new_state == 'zoomed':
            print('maximize event')
        elif self.new_state == 'normal' and self.old_state == 'zoomed':
            print('restore event')
        else:
            print('dragged resize event')


root = Tk()
App(root).pack()
root.mainloop()

If you want to distinguish between dragging the window and dragging to resize, you'll have to add some extra checks, maybe storing the size before <Configure> and the size after, with winfo_height() and winfo_width(), and if no change occurs, you know the window was only repositioned.

Hope that helps.

Upvotes: 4

Related Questions