Alexandru Antochi Alexandru Antochi - 1 month ago 7
Python Question

How can I update Entry without a "submit" button in Tkinter?

So I have

Entries
which have some values assigned to them from a CFG File. I want to modify the CFG file when the
Entry
is updated, live, without a
submit
button;

Using
<Key>
binding will work but will take only the previous value, not the current one, as the last key pressed is not taken into consideration as a value, but as a
key-press
.

For example:

class EntryBox:
def __init__(self, value, option, section, grid_row, master_e):
self.section = section
self.option = option
self.box = Entry(master_e)
self.box.grid(column=0, row=grid_row)
self.serial_no = grid_row
self.box.insert(0, value)
self.box.bind("<Key>", lambda event: update_cfg(event, self, self.get_value()))

def get_value(self):
return self.box.get()


def update_cfg(evt, entry_box,new_value):
global config_file
config_file.set(entry_box.section, entry_box.option, new_value)
print "Config file modified. "+entry_box.section+" "+entry_box.option+" "+new_value


If the value in the
entry
is
05R
when I click on the
entry
and press 6, it will print
Config file modified. CURRENT_MEASUREMENT_EXAMPLE_HP shunt_resistance 05R
; after I press 7, it will print
Config file modified. CURRENT_MEASUREMENT_EXAMPLE_HP shunt_resistance 0R56
and so on, always with one keypress behind. The only way to live update it after the value has been changed is to press the
TAB
or
arrow
buttons.

Answer

You can use either

  • FocusOut
  • tab or enter Key
  • KeyRelease

bindings to achieve that.

Also validation functions can help as they have previous and new values available. Please read the docs for more information on that matter.

It is IMHO the most "pythonic" / "tkinter" way of achieving what is a "check and submit" functionality.

Edit

As stated by OP, binding focusout could lead to problems here an example how it does indeed work:

import Tkinter as tk
import sys

def focus_out_event(event):
    print >> sys.stderr, "Focus-Out   event called with args: %s"%event
    print >> sys.stderr, "Entry Widget Content:               %s"%event.widget.get()
def key_release_event(event):
    print >> sys.stderr, "Key-Release event called with args: %s"%event
    print >> sys.stderr, "Entry Widget Content:               %s"%event.widget.get()

if __name__ == "__main__":
    root = tk.Tk()
    entry1 = tk.Entry(root)
    entry1.bind("", key_release_event)
    entry1.bind("", focus_out_event)
    entry1.grid()

    entry2 = tk.Entry(root)
    entry2.bind("", key_release_event)
    entry2.bind("", focus_out_event)
    entry2.grid()

    root.mainloop()

Test: - enter text ("asd") to entry1 - click into entry2

The last line of output is from changing to screenshot (event that fired a focusout)

Test Result