如何從 Tkinter 文字小工具獲取輸入?
在 tkinter 中,我們可以使用 Text 屬性透過軟體包建立文字小工具。但是,在建立 GUI 應用程式時,有時我們需要獲取文字小工具的輸入。
我們可以使用 .get() 方法獲取文字小工具中的使用者輸入。我們需要指定輸入範圍,最初從 1.0 到 END,表示從開始到 END 結束的字元。
示例
#Import tkinter library from tkinter import * #Create an instance of tkinter window or frame win=Tk() win.geometry("700x300") def get_input(): value=my_text_box.get("1.0","end-1c") print(value) #Creating a text box widget my_text_box=Text(win, height=5, width=40) my_text_box.pack() #Create a button for Comment comment= Button(win, height=5, width=10, text="Comment", command=lambda: get_input()) #command=get_input() will wait for the key to press and displays the entered text comment.pack() win.mainloop()
輸出
執行上述程式碼會顯示一個文字框,該文字框將接受使用者的輸入,然後將輸出列印到控制檯上。
廣告