【发布时间】:2022-01-20 09:05:44
【问题描述】:
我有一个使用文本和按钮小部件的程序。当我按下按钮时,我希望它在文本小部件中插入一个字符串,但我不知道该怎么做。谁能帮帮我?
【问题讨论】:
-
请提供您的代码并生成Minimal Reproduction。
标签: python tkinter button text
我有一个使用文本和按钮小部件的程序。当我按下按钮时,我希望它在文本小部件中插入一个字符串,但我不知道该怎么做。谁能帮帮我?
【问题讨论】:
标签: python tkinter button text
图形用户界面具有键盘焦点(或简称焦点)的概念。具有焦点的小部件将是获取键盘事件的小部件。通常,任何时候都只能有一个具有键盘焦点的小部件。在大多数情况下,焦点是自动处理的。例如,如果您单击文本小部件或条目小部件,则该小部件将获得焦点。
您的问题的答案是调用 tkinter 的 focus_get 方法来获取具有键盘焦点的小部件。然后,您可以调用 insert 方法将文本插入到该小部件中。
下面是一个简单的例子。单击任何文本小部件,然后单击按钮和字符串“Hello!”将插入到具有焦点的任何文本小部件中。
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()
【讨论】: