如何从Python中的文本框中获取字符串?

时间:2014-05-02 12:31:09

标签: python textbox tkinter

我想知道是否可以将文本框中的文本转换为变量(/ string)。 我正在使用Python 3.3.5,我看到很多Entrybox变量,但它不适用于文本框 这是我正在使用的代码:

from tkinter import *

    main = Tk()
    sr=Scrollbar(main)
    a="Hello!"

    txtBox = Text(main, width=20, height=5)
    sr.pack(side=RIGHT)
    txtBox.pack(side=LEFT)
    sr.config(command=txtBox.yview)
    txtBox.config(yscrollcommand=sr.set)
    txtBox.insert(END, a)

    def callback():
        #here is the text converted to a variabel#

    def closewindow():
        exit()

    def save():
        key = #variabel#
        f = open("key.txt", "w")
        f.write(key)
        f.close()
        print(txtBox.get()+(" /has bin saved."))

    button_dsp = Button(main, text="display text", width=10, command=callback)
    button_dsp.pack()

    button_save = Button(main, text="Save", width=10, command=save)
    button_save.pack()

    button_exit = Button(main, text="Exit", width=10, command=closewindow)
    button_exit.pack()
    mainloop()

1 个答案:

答案 0 :(得分:0)

您在保存功能中显示解决方案,但为了您在当前结构中的好处,它看起来有点像这样

def callback():
    return txtBox.get()

def save():
    key = callback()

简化,摆脱回调函数,只需修改你的保存功能:

def save():
    key = txtBox.get()

这当然是假设您不希望条目成为变量的名称。这将是愚蠢的定义。

相关问题