如何从 Tkinter 文本框中获取输入?
Tkinter 文本框小部件用于插入多行文本。此小部件可用于消息传递、显示信息和许多其他任务。重要的任务是获取插入的文本以进行进一步处理。为此,我们必须对文本框小部件使用 get() 方法。
Syntax: get(start, [end])
where,
start is starting index of required text in TextBox
end is ending index of required text in TextBox
If end is not provided, only character at provided start index will be retrieved.
方法:
- 创建 Tkinter 窗口
- 创建一个文本框小部件
- 创建一个按钮小部件
- 创建一个函数,该函数将在点击按钮后使用 get() 方法从文本框中返回文本
下面是实现:
Python3
import tkinter as tk
# Top level window
frame = tk.Tk()
frame.title("TextBox Input")
frame.geometry('400x200')
# Function for getting Input
# from textbox and printing it
# at label widget
def printInput():
inp = inputtxt.get(1.0, "end-1c")
lbl.config(text = "Provided Input: "+inp)
# TextBox Creation
inputtxt = tk.Text(frame,
height = 5,
width = 20)
inputtxt.pack()
# Button Creation
printButton = tk.Button(frame,
text = "Print",
command = printInput)
printButton.pack()
# Label Creation
lbl = tk.Label(frame, text = "")
lbl.pack()
frame.mainloop()
输出: