Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert the same text in differents entry widget with same button is clicked Tkinter

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you have any suggestions, I would be very grateful, please.

Thank you very much!

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading