简体   繁体   English

按下按钮时如何修改 tKinter 中选定的文本小部件?

[英]How to modify a selected text widget in tKinter when pressing a button?

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?有人可以帮我吗?

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.您的问题的答案是调用 tkinter 的focus_get方法来获取具有键盘焦点的小部件。 You can then call the insert method to insert text into that widget.然后,您可以调用insert方法将文本插入该小部件。

The following is a simple example.下面是一个简单的例子。 Click on any text widget and then click the button, and the string "Hello."单击任何文本小部件,然后单击按钮和字符串“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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM