所以我有 Entries
从 CFG 文件中为它们分配了一些值。我想在 Entry
时修改 CFG 文件已更新,实时,没有 submit
按钮;
使用 <Key>
绑定(bind)将起作用,但将仅采用先前的值,而不是当前值,因为最后按下的键不被视为值,而是作为 key-press
.
例如:
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
如果 entry
中的值是05R
当我点击 entry
然后按 6,它会打印 Config file modified. CURRENT_MEASUREMENT_EXAMPLE_HP shunt_resistance 05R
;按 7 后,它会打印 Config file modified. CURRENT_MEASUREMENT_EXAMPLE_HP shunt_resistance 0R56
依此类推,总是在后面按下一个键。更改值后实时更新它的唯一方法是按 TAB
。或 arrow
纽扣。
最佳答案
你可以使用任何一个
FocusOut
tab
或enter
键KeyRelease
绑定(bind)来实现这一点。
验证函数也可以提供帮助,因为它们具有可用的旧值和新值。请阅读docs有关该问题的更多信息。
恕我直言,这是实现“检查和提交”功能的最“pythonic”/“tkinter”方式。
编辑
如 OP 所述,绑定(bind) focusout
可能会导致问题,这里是一个示例,它确实是如何工作的:
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()
测试: - 输入文本(“asd”)到 entry1 - 点击进入entry2
输出的最后一行是从更改为屏幕截图(触发focusout
的事件)
关于python - 如何在 Tkinter 中没有 "submit"按钮的情况下更新条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957699/