I want to create a button in tkinter that prints text in different Entry
depends if it clicked. The text to be displayed must be the same, but not at the same time.
I have this code to try to get the result:
from tkinter import *
root = Tk()
event = StringVar()
def callback(event):
print("focus in event raised, open keyboard")
return event
frame = Frame(root, width=100, height=100)
frame.pack()
addressInput = Entry(frame, font = "Verdana 20 ", justify="center")
addressInput.bind("<FocusIn>", callback)
addressInput.pack()
addressInput.focus_set()
otroInput = Entry(frame, font = "Verdana 20 ", justify="center")
otroInput.bind("<FocusIn>", callback)
otroInput.pack()
def inserta(text):
if event == ".!frame.!entry":
addressInput.insert(200,text)
if event == ".!frame.!entry2":
otroInput.insert(200,text)
inserta=Button(frame, text="Insert number 2 ", command=inserta("2"))
inserta.pack()
root.mainloop()
So when I click inserta(Buttom)
in addressInput(entry)
you can see the number "2". If you select otroInput(Entry)
and then click the Button, you see number "2" in otroInput(Entry)
.
If you have any suggestions, I would be very grateful, please.
Thank you very much!
If you want the text to be inserted into the widget with keyboard focus, you can use focus_get()
to get the widget with the focus. You can then check to see if it's an entry widget, and insert text into it if it is.
def inserta():
focus = root.focus_get()
if focus and focus.winfo_class() == "Entry":
focus.insert("insert", "a")
...
inserta=Button(frame, text="Insert number 2 ", command=inserta)
If you want to be able to pass in what is to be inserted, you can use lambda
to create an anonymous function:
def do_insert(char):
focus = root.focus_get()
if focus and focus.winfo_class() == "Entry":
focus.insert("insert", char)
...
insert2=Button(frame, text="Insert number 2 ", command=lambda: do_insert("2")