首页 > 解决方案 > 单击tkinter中的按钮时返回一个值

问题描述

我创建了一个简单的文本框,并希望在单击按钮时从中获取文本,但由于某种原因它不起作用。我尝试使用全局变量,但它仍然不起作用。这是我到目前为止所写的:

t = Text(r, height=20, width=40)
t.pack()

def myClick():
    myLabel= Label(r,text= "Sent!")
    global input
    input = t.get("1.0", 'end-1c')
    myLabel.pack()




myButton = Button(r, text="Send ", command=myClick)
myButton.pack()
print(input)
r.mainloop()

标签: pythontkinter

解决方案


.get()我认为您在和小部件类型中使用了太多参数, Entry并且您确实应该在其他所有内容之前定义您的变量。这是我对您的代码的建议:

from tkinter import *

r = Tk()

t = Entry(r, width=40)
t.pack()

def myClick():
    global input
    input = t.get()
    myLabel= Label(r,text= input)
    myLabel.pack()

myButton = Button(r, text="Send ", command=myClick)
myButton.pack()
print(input)
r.mainloop()

推荐阅读