continuous call of the Configure event in tkinter

后端 未结 2 1823
情话喂你
情话喂你 2021-01-20 01:50

I am trying to write a function to dynamically resize an image displayed in a tkinter window. Therefore I bound this function to the Configure event:

connroot.

相关标签:
2条回答
  • 2021-01-20 02:25

    1) We don't know that, since we can't see your code...

    2) Short answer is: you can't, because that's exactly what <Configure> event does! Long answer, you can, with a little trick/hack. Since anytime the window is changing, it will call all the binded functions to <Configure>, and the same happens anytime as the mouse button released (right after the last <Configure> call) we can create a flag/switch which will tell us, if the window was "configured" then we can check that switch anytime the mouse button is released, and switch it back to the default value after we ran some actions.

    So if you want the image to resized only, when the mouse was released and the window was changed this is the code you need:

    from tkinter import *
    
    class Run:
        def __init__(self):
            self.root = Tk()
            self.clicked = False
            self.root.bind('<ButtonRelease-1>', self.image_resize)
            self.root.bind('<Configure>', lambda e: self.click(True))
        def image_resize(self, event):
            if self.clicked:
                print("I'm printed after <Configure>.")  # the action goes here!
                self.click(False)
        def click(self, value):
            self.clicked = value
    
    app = Run()
    app.root.mainloop()
    
    0 讨论(0)
  • 2021-01-20 02:43

    According to the official tk documentation, <Configure> events fire "whenever its size, position, or border width changes, and sometimes when it has changed position in the stacking order." This can happen several times during startup.

    It is called continuously while you resize the window because the size of the widget is changing. That's what it's defined to do. You can't prevent it from being called, though you can certainly modify what you do in the callback. For example, you could delay resizing the image until you've not received another <Configure> event for a second or two -- which likely means the user has stopped interactive resizing.

    0 讨论(0)
提交回复
热议问题