Tkinter 텍스트 상자에서 입력을 얻는 방법
Tkinter Text 위젯에는 start 위치 인수가있는 텍스트 상자에서 입력을 반환하는 get()메소드와 가져올 텍스트의 끝 위치를 지정하는 end 인수 (선택 사항)가 있습니다.
get(start, end=None)
end 가 주어지지 않으면 start 위치에 지정된 하나의 문자 만 반환됩니다.
Tkinter 텍스트 위젯에서 입력을 가져 오는 예제 코드
import tkinter as tk
root = tk.Tk()
root.geometry("400x240")
def getTextInput():
result = textExample.get("1.0", "end")
print(result)
textExample = tk.Text(root, height=10)
textExample.pack()
btnRead = tk.Button(root, height=1, width=10, text="Read", command=getTextInput)
btnRead.pack()
root.mainloop()
result = textExample.get("1.0", "end")
‘텍스트’위젯에서 첫 번째 문자의 위치는 1.0이며 숫자 1.0또는 문자열 1.0입니다.
“끝"은 텍스트 상자가 끝날 때까지 입력을 읽는 것을 의미합니다. 또한 문자열 "end" 대신 tk.END 를 사용할 수도 있습니다.

리턴 할 텍스트의 끝 위치로 "end"를 지정하면 위의 애니메이션에서 볼 수 있듯이 텍스트 문자열의 끝에 줄 바꿈 \n 문자도 포함됩니다.
입력에 개행 문자를 원하지 않으면 get 메소드의 "end" 인수를"end-1c"로 변경할 수 있습니다.
"end-1c"는 위치가 "end" 보다 한 문자 앞에 있다는 것을 의미합니다.
Tkinter Text 위젯의 끝에서 ‘줄 바꾸기’없이 입력을 가져 오는 예제 코드
import tkinter as tk
root = tk.Tk()
root.geometry("400x240")
def getTextInput():
result = textExample.get(1.0, tk.END + "-1c")
print(result)
textExample = tk.Text(root, height=10)
textExample.pack()
btnRead = tk.Button(root, height=1, width=10, text="Read", command=getTextInput)
btnRead.pack()
root.mainloop()

여기에서는 마지막 문자 인\n 을 제거하기 위해 "end-1c"외에 tk.END+"-1c"를 사용할 수도 있습니다.tk.END = "end"이므로 tk.END+"-1c"는"end"+"-1c"="end-1c"와 같습니다.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook