tkinter clicks on child do not propagate to parent - python

Why doesn't clicking on a child element propagate to the parent?
from tkinter import *
root = Tk()
def handler(event):
print('clicked at', event.x, event.y)
frame = Frame(root, width=100, height=100)
label = Label(frame, text="Label")
frame.bind('<Button-1>', handler)
frame.pack()
label.pack(side=TOP)
root.mainloop()
When I run that, clicking on the label doesn't fire the handler. I've understood that events propagate to parents by default and if you didn't want that, you'd have to return "break"

You are incorrect in your original understanding that events propagate to their parent. They do not.
Admittedly, there's an edge case for widgets which are a direct descendant of a toplevel or root window. Even there, it's not that they are propagating to their parent, but rather they are being handled by other bindings as defined by the bind tags, and by default every widget has it's toplevel window as one of it's bind tags.
If you want to set a binding to work everywhere you can use the bind_all method, since each widget has an "all" bindtag by default. Another option is to give several widgets the same bindtag (using the bindtags method), then bind to that bindtag with bind_class. Which choice you make depends on what you are trying to accomplish.
bindtags are extremely powerful -- arguably more powerful than any binding mechanisms from any other toolkit. For example, if you need to have events propagate you can do that by adjusting the bindtags of every widget to include all of its ancestors. In my experience, however, such shenanigans is rarely ever needed.

You're mistaken. "break" causes that event to not propagate to other handlers for the widget that was clicked on.
In other words, if you bound your action to label and then you bound another action to the first button onto label, both callbacks will be called (unless you return "break" from the first one to be called.)
I'm not sure of a workaround though ... (We might need to wait for BryanOakley to show up ;)

Related

Python tkinter override default ctrl-h binding

I have no problem with binding ctrl-h. However, when I do the ctrl-h, I notice that the last character is also removed from the entry. I think this might be the default ctrl-h binding of python. How can I disable that?
---Update---
I have added the return 'break' thing. But it still doesn't work. The last character is immediately removed before the askstring dialog shows up. Here is the code that is bound.
def replace(self):
target = simpledialog.askstring(title = 'Replace', prompt = 'Replace Target')
if not target:
return 'break'
withValue = simpledialog.askstring(title = 'Replace', prompt = 'Replace With')
if not withValue:
return 'break'
for entry in self.entries.values():
setEntry(entry, entry.get().replace(target, withValue))
return 'break'
By the way I bind it with the master not the entry because I have a lot of entries. Binding with the master is way easier.
This is how I bind it.
self.master.bind('<Control-h>', lambda event: self.replace())
self.master is defined here:
class Generator(Frame):
def __init__(self, master):
Frame.__init__(self, master)
## init variables
self.master = master
This is what I pass in.
root = Tk()
gui = Generator(root)
gui.pack()
root.title('Generator')
root.mainloop()
Because you are binding to the root window rather than an individual widget, there's nothing you can do in your function. Bindings are processed in this order:
bindings on a specific widget
bindings on a widget class
bindings on the toplevel window in which the widget exists
bindings on the special tag "all"
If at any time in the processing of those bindings a function returns the string "break", no further processing will happen. Thus, if you have a binding on a specific widget and return "break", the default class binding won't be processed. However, if you return "break" from a binding to the root window, that binding isn't processed until after the class binding. Therefore, it's impossible for this sort of binding to prevent the default behavior.
However, tkinter bindings are remarkably customizable, so there are solutions. Given that you potentially want to inhibit the default behavior, the most straight-forward solution is to either bind to the class so that you completely replace the default behavior, or bind to each widget individually so that you can prevent the class binding from happening.
If you really want the binding to be universal by binding to the root window, then the easiest solution might be to change the order of processing for all widgets that have default bindings for control-h.
For example, to move the handling of root-level bindings before class-level bindings, you can do something like this:
entry = tk.Entry(root)
bindtags = entry.bindtags()
entry.bindtags((bindtags[2], bindtags[0], bindtags[1], bindtags[3]))
For more information on exactly how bindings are processed, you might want to look at the following questions:
Basic query regarding bindtags in tkinter
How to bind self events in Tkinter Text widget after it will binded by Text widget?
Here is a simple example that binds to the root window, but changes the bind tags so that the default binding can be defeated by returning "break":
import tkinter as tk
def custom_backspace(event):
entry.insert("insert", "<backspace>")
return "break"
root = tk.Tk()
entry = tk.Entry(root)
entry.pack(fill="x")
bindtags = entry.bindtags()
entry.bindtags((bindtags[2], bindtags[0], bindtags[1], bindtags[3]))
root.bind("<Control-h>", custom_backspace)
root.mainloop()

Python tkinter: Delete Menu checkbutton

I want to delete a menu checkbutton when i right click on it.
Its usually done with bind("Mouse3", deletefunction) , BUT i need an actual instance of a checkbutton to bind it with, and the only way to add a checkbutton to a menu i know is a add_checkbutton() method (and i have no access to instance this way). Is there any way i could do this?
import tkinter as tk
root = tk.Tk()
menubar = tk.Menu(root)
view_menu = tk.Menu(menubar, tearoff=0)
view_menu.add_checkbutton(label="Right click on me to delete", onvalue=1, offvalue=False)
# I want to do something like this:
# c = Checkbutton(label="Right click on me to delete")
# c.bind("Mouse3", my_delete_function())
# view_menu.add(c)
menubar.add_cascade(label='View', menu=view_menu)
root.config(menu=menubar)
root.mainloop()
To the best of my understanding, there's essentially two parts to your question:
Can the menu bar item be assigned for manipulation after?
Can the referenced item be then bound to an event?
The first answer is, sort of. While you can't exactly assign the object, you can reference it by index like this:
view_menu.delete(0)
Since you added the checkbutton first, it'll have an index of 0. You can either keep track of the indices, or refer to the item by its label. See this related answer from Bryan Oakley. e.g.:
view_menu.delete(view_menu.index("Right click on me to delete"))
The .index() method will locate the index by the menu entry's label, which can be handy unless you have the same label more than once...
The second answer, as far as I'm aware, there doesn't seem to be any effective binding for typical events like mouse clicks. However after some search I did come across a rather hidden <<MenuSelect>> binding that at least triggers an event. That by itself is not useful to your quest, but you can combine the event state with the checkbutton's command argument as well as a boolean flag to trigger an event on click:
# Add a BooleanVar for flagging:
delete_checkbutton = tk.BooleanVar()
# Add a binding to your view_menu
view_menu.bind('<<MenuSelect>>', event_state)
# Define the callback function:
def event_state(e):
if bool(e.state & 0x0400): # watch for the Mouse Right click state
# you might opt to use 0x0004 or 0x0001 instead
# i.e. Ctrl+click or Shift+Click
delete_checkbutton.set(True)
else: # If the state is not right click, reset the flag
delete_checkbutton.set(False)
# Define a self_delete command for the checkbutton
def self_delete():
if delete_checkbutton.get():
view_menu.delete(view_menu.index("Right click on me to delete"))
# Add the command to your checkbutton
view_menu.add_checkbutton(label="Right click on me to delete", onvalue=lambda:print('hey'), offvalue=False, command=self_delete)
Note: You will actually have to hold right click and then left click on the checkbutton to delete it. Obviously the drawback is you have now triggered the on/off value, and you might need to have some additional handling on those.
If right + left click is too awkward, Ctrl/Shift is another mod state you might consider.
Another side note: I'm a proponent of OOP when it comes to tkinter, it makes accessible variables and flags much easier without needing to worry the global and nonlocal namespaces. Here since delete_checkbutton is set in the global namespace I avoied using the global keyword and accessed it via the tk.BooleanVar() object. However if you were to use a python boolean (e.g. flag = True) then it won't be as effective unless you indicate global flag in both functions. If however you took an OOP approach you can reference the flags directly via self.flag without ambiguity.
Finally, here are the comprehensive changes implemented into your code for sampling:
import tkinter as tk
def event_state(e):
if bool(e.state & 0x0400):
# you might opt to use 0x0004 or 0x0001 instead
# i.e. Ctrl+click or Shift+Click
delete_checkbutton.set(True)
else:
delete_checkbutton.set(False)
def self_delete():
if delete_checkbutton.get():
view_menu.delete(view_menu.index("Right click on me to delete"))
root = tk.Tk()
menubar = tk.Menu(root)
delete_checkbutton = tk.BooleanVar()
view_menu = tk.Menu(menubar, tearoff=0)
view_menu.add_command(label='dude', command=lambda: print('dude'))
view_menu.add_checkbutton(label="Right click on me to delete", onvalue=lambda:print('hey'), offvalue=False, command=self_delete)
menubar.add_cascade(label='View', menu=view_menu)
root.config(menu=menubar)
view_menu.bind('<<MenuSelect>>', event_state)
root.mainloop()
All that said, I am of the opinion that this is not a very smooth User Experience and is somewhat confusing. Just the permanent deletion of the menu item alone is questionable at best, combined with the method you are trying to call upon the deletion feels even more contrived. I'd suggest revisiting your UX flow to consider how to streamline this.

How can I set the focus to a widget (that isn't an entry) by clicking on it?

The reason I need to do this is because I need to change the text of a label without having to use entries; I want to use events instead.
I have tried this:
import tkinter as tk
root = tk.Tk()
root.bind("<Button-1>", lambda _: root.focus())
l = tk.Label(root, width=50, height=50, bg="white")
l.bind("<Button-1>", lambda _: l.focus())
l.bind("1", lambda _: l.config(bg="yellow"))
l.bind("2", lambda _: l.config(bg="white"))
l.pack()
root.mainloop()
When I ran the program, I expected to be able to change the colour of the label l to yellow by clicking on it (which I thought would set the focus to it) then pressing 1, and changing it back to white by pressing 2; provided that I didn't click outside of the label and set the focus to the root widget (where the keys 1 and 2 weren't bound to any callback).
I know that you can bind keys to callbacks (tested it), and I also know that it is possible to set the focus to widgets which aren't entries (tested that too), yet this doesn't seem to work.
Can anybody help me?
The problem is that you have two bindings for a button click: one on the label widget itself and one on the root window. Because of the way that events are processed, the binding on the root window will fire after the event on the label. That means that whatever focus you set on the label binding will get undone with the binding on the root window.
One solution is to change your binding on the click to set the focus to whatever was clicked on. With that, you don't need to set a binding on the label widget for a click.
root.bind("<Button-1>", lambda event: event.widget.focus_set())
Another solution would be to modify your binding on the label to prevent the binding on the root window from firing. You can do that by returning the string "break" from the function that is called.
def callback(event):
l.focus()
return "break"
l.bind("<Button-1>", callback)

How to capture events on tkinter child widgets?

In the following block, clicking on a_frame triggers the event handler on_frame_click, but clicking on a_label which is a child of a_frame does not. Is there a way to force a_frame to trap and handle events which originated on it's children (preferably with out having to add handlers to the children directly)? I am using Python 3.2.3.
import tkinter
def on_frame_click(e):
print("frame clicked")
tk = tkinter.Tk()
a_frame = tkinter.Frame(tk, bg="red", padx=20, pady=20)
a_label = tkinter.Label(a_frame, text="A Label")
a_frame.pack()
a_label.pack()
tk.protocol("WM_DELETE_WINDOW", tk.destroy)
a_frame.bind("<Button>", on_frame_click)
tk.mainloop()
Yes, you can do what you want, but it requires a bit of work. It's not that it's not supported, it's just that it's actually quite rare to need something like this so it's not the default behavior.
TL;DR - research "tkinter bind tags"
The Tkinter event model includes the notion of "bind tags". This is a list of tags associated with each widget. When an event is received on a widget, each bind tag is checked to see if it has a binding for the event. If so, the handler is called. If not, it continues on. If a handler returns "break", the chain is broken and no more tags are considered.
By default, the bind tags for a widget are the widget itself, the widget class, the tag for the toplevel window the widget is in, and finally the special tag "all". However, you can put any tags you want in there, and you can change the order.
The practical upshot of all this? You can add your own unique tag to every widget, then add a single binding to that tag that will be processed by all widgets. Here's an example, using your code as a starting point (I added a button widget, to show this isn't something special just for frames and labels):
import Tkinter as tkinter
def on_frame_click(e):
print("frame clicked")
def retag(tag, *args):
'''Add the given tag as the first bindtag for every widget passed in'''
for widget in args:
widget.bindtags((tag,) + widget.bindtags())
tk = tkinter.Tk()
a_frame = tkinter.Frame(tk, bg="red", padx=20, pady=20)
a_label = tkinter.Label(a_frame, text="A Label")
a_button = tkinter.Button(a_frame, text="click me!")
a_frame.pack()
a_label.pack()
a_button.pack()
tk.protocol("WM_DELETE_WINDOW", tk.destroy)
retag("special", a_frame, a_label, a_button)
tk.bind_class("special", "<Button>", on_frame_click)
tk.mainloop()
For more on bindtags, you might be interested in my answer to the question How to bind self events in Tkinter Text widget after it will binded by Text widget?. The answer addresses a different question than the one here, but it shows another example of using bind tags to solve real world problems.
I can't seem to find a direct method of automatically binding to child widgets (though there are methods of binding to an entire class of widgets and to all widgets in an application), but something like this would be easy enough.
def bind_tree(widget, event, callback, add=''):
"Binds an event to a widget and all its descendants."
widget.bind(event, callback, add)
for child in widget.children.values():
bind_tree(child, event, callback, replace_callback)
Just thought of this, but you could also put a transparent widget the size of a_frame on top of everything as a child of a_frame and bind the <Button> event to that, and then you could refer to a_frame as e.widget.master in the callback in order to make it reusable if necessary. That'd likely do what you want.
Based on what it says in the Levels of Binding section of this online Tkinter reference, it sounds like it's possible because you can bind a handler to three different levels.
To summarize:
Instance Level: Bind an event to a specific widget.
Class Level: Bind an event to all widgets of a specific class.
Application Level: Widget independent -- certain events always invoke a specific handler.
For the details please refer to the first link.
Hope this helps.
Depending on what you're trying to do, you could bind everything
print(a_label.bindtags()) # ('.!frame.!label', 'Label', '.', 'all')
tk.bind_class('.', "<Button>", on_frame_click)

Tkinter toplevel communication

If I have a button that executes a handler in relation to one toplevel window or root - can it modify a widget in another toplevel? What is the standard method of doing this?
I am not experienced in Tkinter, but I am sure its no different than PyQt4. Generally you want the parent child relationship. A parent widget contains children widgets and can modify them. The children should usually not know much about their parents and would communicate via signals or events.
When a handler fires, it should be free to modify the widgets it knows about. That is, if your top level window has 10 widgets, and contains the handler as a method, the method should be allowed to modify the 10 widgets through self attributes.
Something like:
class MyTopWindow:
def __init__(self):
self.widget1 = Widget
self.widget2 = Widget
self.button = Button
#self.button.clicked -> self.handler
def handler(self):
self.widget1.someAttribute = 1
button.click() # -> handler()
You make use of composition to build widgets inside of widgets. What you should avoid is a handler making some reference to a global widget that it really does not own.
Yes, a handler for a button (or any event) can modify any widget in any other toplevel. As long as that handler has a reference to the widget, the handler can modify it. There are no restrictions in that regard.

Categories