如何从Tkinter文本组件获取输入?
如何从Text
组件获取Tkinter输入?
编辑
我问这个问题是为了帮助其他遇到同样问题的人——这就是为什么没有示例代码的原因。这个问题困扰了我好几个小时,我用这个问题来教别人。请不要把它当作一个真正的问题来评分——答案才是最重要的。
9 个回答
9
要在Python 3中从文本框获取Tkinter的输入,我用的完整学生级别的程序如下:
#Imports all (*) classes,
#atributes, and methods of tkinter into the
#current workspace
from tkinter import *
#***********************************
#Creates an instance of the class tkinter.Tk.
#This creates what is called the "root" window. By conventon,
#the root window in Tkinter is usually called "root",
#but you are free to call it by any other name.
root = Tk()
root.title('how to get text from textbox')
#**********************************
mystring = StringVar()
####define the function that the signup button will do
def getvalue():
## print(mystring.get())
#*************************************
Label(root, text="Text to get").grid(row=0, sticky=W) #label
Entry(root, textvariable = mystring).grid(row=0, column=1, sticky=E) #entry textbox
WSignUp = Button(root, text="print text", command=getvalue).grid(row=3, column=0, sticky=W) #button
############################################
# executes the mainloop (that is, the event loop) method of the root
# object. The mainloop method is what keeps the root window visible.
# If you remove the line, the window created will disappear
# immediately as the script stops running. This will happen so fast
# that you will not even see the window appearing on your screen.
# Keeping the mainloop running also lets you keep the
# program running until you press the close buton
root.mainloop()
32
这是我用 Python 3.5.2 实现的方法:
from tkinter import *
root=Tk()
def retrieve_input():
inputValue=textBox.get("1.0","end-1c")
print(inputValue)
textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Commit",
command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()
mainloop()
这样一来,当我在文本框里输入“blah blah”并按下按钮时,我输入的内容就会被打印出来。所以我觉得这就是把用户在文本框中输入的内容存储到变量里的方法。
215
要从Tkinter的文本框中获取输入,你需要在普通的 .get()
函数上加一些额外的设置。如果我们有一个文本框叫 myText_Box
,那么获取它输入的方法就是这样。
def retrieve_input():
input = self.myText_Box.get("1.0",END)
这里的第一部分 "1.0"
表示从第一行的第一个字符开始读取输入,也就是文本框里的第一个字符。END
是一个常量,它的值是字符串 "end"
。END
的意思是一直读取到文本框的末尾。不过,这样做有个问题,就是会多出一个换行符。所以,为了解决这个问题,我们应该把 END
改成 end-1c
(感谢 Bryan Oakley)。这里的 -1c
是指删除一个字符,而 -2c
则是删除两个字符,以此类推。
def retrieve_input():
input = self.myText_Box.get("1.0",'end-1c')