Leo
Leo

Reputation: 11

Python - tkinter interface, using bind works only the first time (when running the program)

I'm attaching the code below. There is an event on "focus out", the event triggers once when the code is initialized. Afterwards focusing out of the Spinbox does not trigger the event anymore. The question is, why? And, how do I fix that?

code :

import tkinter as tk
import os, time

def spinBoxValidateRange(widget_name):
    print(str(widget_name.winfo_name()) + " focus out")
   

# Making a window, and giving it some settings
root = tk.Tk()
root.resizable(False, False)
root.winfo_toplevel().title("Test")
# creating a user GUI
default_pady = 2
default_padx = 5

sbx_max_img_width = tk.Spinbox(from_=500, to=5000, width = 4)
sbx_max_img_width.delete(0, 'end')
sbx_max_img_width.insert(0, 1000)
sbx_max_img_height = tk.Spinbox(from_=500, to=5000, width = 4)
sbx_max_img_height.delete(0, 'end')
sbx_max_img_height.insert(0, 1000)
sbx_max_img_width.grid(row = 0, column = 1, sticky = "W", pady = default_pady, padx = default_padx)
sbx_max_img_height.grid(row = 0, column = 3, sticky = "W", pady = default_pady, padx = default_padx)
sbx_max_img_width.bind("<FocusOut>", spinBoxValidateRange(sbx_max_img_width))
sbx_max_img_height.bind("<FocusOut>", spinBoxValidateRange(sbx_max_img_height))

root.mainloop()

Upvotes: 0

Views: 189

Answers (1)

Leo
Leo

Reputation: 11

Here is the corrected code (that works) -

import tkinter as tk
import os, time

def spinBoxValidateRange(some_widget):
    print(str(some_widget.widget.winfo_name()) + " focus out")
   

# Making a window, and giving it some settings
root = tk.Tk()
root.resizable(False, False)
root.winfo_toplevel().title("Test")
# creating a user GUI
default_pady = 2
default_padx = 5

sbx_max_img_width = tk.Spinbox(from_=500, to=5000, width = 4)
sbx_max_img_width.delete(0, 'end')
sbx_max_img_width.insert(0, 1000)
sbx_max_img_height = tk.Spinbox(from_=500, to=5000, width = 4)
sbx_max_img_height.delete(0, 'end')
sbx_max_img_height.insert(0, 1000)
sbx_max_img_width.grid(row = 0, column = 1, sticky = "W", pady = default_pady, padx = default_padx)
sbx_max_img_height.grid(row = 0, column = 3, sticky = "W", pady = default_pady, padx = default_padx)
sbx_max_img_width.bind("<FocusOut>", lambda parameter = sbx_max_img_width: spinBoxValidateRange(parameter))
sbx_max_img_height.bind("<FocusOut>", lambda parameter = sbx_max_img_height: spinBoxValidateRange(parameter))

root.mainloop()

Upvotes: 1

Related Questions