[SOLVED] Tkinter – Seperate ‘Button’ class with different TopLevel

Issue

This Content is from Stack Overflow. Question asked by Seminet

I have a problem with bind_class. I want to bind some events for all buttons in my topLevel mainWindow. But my other topLevel themeWindow‘s buttons also effected from this.

My code:

root = tk.Tk()
mainWindow = Toplevel(root)
themeWindow = Toplevel(root)
#my buttons and labels
mainWindow.bind_class('Button', '<Enter>', onCursorButton, add='+')
mainloop()

And themeWindow‘s buttons keep effecting from <Enter> and <Leave> event.



Solution

Try this code:

import tkinter as tk


def get_masters(widget):
   output = []
   while widget.master is not None:
      widget = widget.master # Get the widgets master
      output.append(widget)  # Append it to the list
      if isinstance(widget, tk.Toplevel): # If we incounter a toplevel stop
         break
   return output


def function(event):
   print("Is the widget's master `main_window`?: ", main_window in get_masters(event.widget))
   # Check if the widget that caused the event is in `main_window`
   if main_window in get_masters(event.widget):
      print("Hangle event")
   else:
      print("Ignore event")


root = tk.Tk()
main_window = tk.Toplevel(root)
theme_window = tk.Toplevel(root)

button = tk.Button(main_window, text="Main Window")
button.pack()

button = tk.Button(theme_window, text="Theme Window")
button.pack()

main_window.bind_class("Button", "<Enter>", function, add="+")
root.mainloop()

The function get_masters returns a list of all of the frames+window that the widget is in. In function, we check if the widget that caused the even is in main_window or not. Based on that we can either handle or ignore the event.


This Question was asked in StackOverflow by Seminet and Answered by TheLizzard It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?