从文本 tkinter 传递值

Passing value from text tkinter

我正在尝试传递用户在运行时使用 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 个问题:

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

这应该给你你想要的行为:

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

button.config(command=call)

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