Home > Back-end >  How to modify a selected text widget in tKinter when pressing a button?
How to modify a selected text widget in tKinter when pressing a button?

Time:12-18

I have a program that uses text and button widgets. I want it to insert a string in the text widget when I press the button, but I have no idea of how to do that. Could anyone help me?

CodePudding user response:

Graphical user interfaces have the concept of keyboard focus (or focus for short). A widget with the focus will be the widget that gets keyboard events. Normally there can only be a single widget with the keyboard focus at any one time. For the most part, focus is handled automatically. For example, if you click in a text widget or entry widget, that widget will be given the focus.

The answer to your question is to call tkinter's focus_get method to get the widget with the keyboard focus. You can then call the insert method to insert text into that widget.

The following is a simple example. Click on any text widget and then click the button, and the string "Hello!" will be inserted in whichever text widget has the focus.

import tkinter as tk

def insert_hello():
    widget = root.focus_get()
    widget.insert("end", "Hello!")

root = tk.Tk()
button = tk.Button(root, text="Hello", command=insert_hello)
button.pack(side="top")
for i in range(3):
    text = tk.Text(root, width=40, height=4)
    text.pack(side="top", fill="both", expand=True)

root.mainloop()
  • Related