如何从Tkinter Text Box Widget获得input?

如何从Python 2.7.3中的文本框中获取Tkinterinput?

编辑

我问了这个问题,以帮助其他同样的问题 – 就是没有示例代码的原因。 这个问题困扰了我几个小时,我用这个问题来教别人。 不要评价它是一个真正的问题 – 答案是重要的。

要从文本框中获取Tkinterinput,您必须在常规的.get()函数中添加更多的属性。 如果我们有一个文本框myText_Box ,那么这是检索其input的方法。

 def retrieve_input(): input = self.myText_Box.get("1.0",END) 

第一部分, "1.0"表示input应该从第一行字符零(即:第一个字符)读取。 END是一个被设置为string"end"的导入常量。 END部分意味着阅读,直到文本框结束。 唯一的问题是,它实际上为我们的input添加了一个换行符。 所以,为了解决这个问题,我们应该把END改成end-1c (谢谢Bryan Oakley ) -1c删除1个字符,而-2c意味着删除两个字符,依此类推。

 def retrieve_input(): input = self.myText_Box.get("1.0",'end-1c') 

这是我用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() 

与此同时,当我在文本小部件中input“blah blah”并按下button时,无论我input什么,都会打印出来。 所以我认为这是将用户input从文本小部件存储到variables的答案。

为了从python 3的文本框中获得Tkinterinput,我使用的完整的学生级程序如下:

 #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()