如何在 Tkinter 中列印並在文字框中獲取使用者輸入?


我們可以使用 Tkinter 文字小部件來插入文字、顯示資訊和獲取文字小部件的輸出。如果要在文字小部件中獲取使用者輸入,我們必須使用 get() 方法。下面我們舉個例子來看看它是如何工作的。

示例

# Import the required library
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win=Tk()

# Set the geometry
win.geometry("700x350")

def get_input():
   label.config(text=""+text.get(1.0, "end-1c"))

# Add a text widget
text=Text(win, width=80, height=15)
text.insert(END, "")
text.pack()

# Create a button to get the text input
b=ttk.Button(win, text="Print", command=get_input)
b.pack()

# Create a Label widget
label=Label(win, text="", font=('Calibri 15'))
label.pack()

win.mainloop()

輸出

執行上述程式碼會顯示一個包含文字小部件的視窗。在文字小部件中輸入一些內容,然後單擊 **“列印”** 按鈕來顯示輸出。

更新日期:2021 年 8 月 5 日

8K+ 檢視

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.