从文本tkinter传递值

时间:2017-05-18 09:16:05

标签: python tkinter tkinter-canvas

我正在尝试使用text.get()

传递用户在运行时在文本框中输入的值

我正在使用以下代码:

from tkinter import *
from tkinter import ttk

root = Tk()
#LABEL
label = ttk.Label(root,text = 'FUNCTION CALL')
label.pack()
label.config(justify = CENTER)
label.config(foreground = 'blue')

Label(root, text="ENTER TEXT: ").pack()

#TEXTBOX
text = Text(root,width = 40, height = 1)
text.pack()
text_value = text.get('1.0', '1.end')

#BUTTON
button = ttk.Button(root, text = 'PASS')
button.pack() 

#FUNCTION DEF
def call(text_value):
    print(text_value)

button.config(command = call(text_value))   

root.mainloop()

然而,在文本框中的文本传递到函数并打印

之前,程序已完全执行

如何从文本框中获取用户输入并将其传递给函数,然后单击按钮执行该函数

2 个答案:

答案 0 :(得分:2)

1:Why is Button parameter “command” executed when declared

2:另一个问题 - 您试图在mainloop之前获得用户输入且只有一次,因此根本没有用户输入。要克服这一点 - 在按钮点击事件(当你真的需要它时)获得用户输入:

...
#TEXTBOX
text = Text(root,width = 40, height = 1)
text.pack()

#BUTTON
button = ttk.Button(root, text = 'PASS')
button.pack()

#FUNCTION DEF
def call():
    text_value = text.get('1.0', '1.end')
    print(text_value)

button.config(command = call)

root.mainloop()

答案 1 :(得分:0)

你有两个问题:

  • 首先,文本框的text_value内容只读取一次,因此在用户输入内容后不会更新。
  • 其次,将命令绑定到按钮时,必须传递函数句柄,而不是调用函数(参见here)。

这可以为您提供所需的行为:

def call():
    print(text.get('1.0', '1.end'))

button.config(command=call)