Python 从文本tkinter传递值
我试图通过text.get()传递用户在运行时在文本框中输入的值 以下代码是我正在使用的代码:Python 从文本tkinter传递值,python,tkinter,tkinter-canvas,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
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()
但是,在将文本框中的文本传递到函数并打印之前,程序将完全执行
如何从文本框中获取用户输入并将其传递到函数中,然后单击按钮执行该函数,您有两个问题:
- 首先,文本框的
内容只读取一次,因此在用户键入内容后不会更新李>text\u值
- 其次,将命令绑定到按钮时,必须传递函数句柄,而不是调用函数(请参阅)
def call():
print(text.get('1.0', '1.end'))
button.config(command=call)
1:
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()