Python使用tkinter无法获取Entry输入框内容如何解决?
问题原因
你调用的是Entry类的get()方法,而非你实例化生成的输入框对象的对应方法,同时打印的目标是Entry类本身,自然无法输出你输入的内容。你创建的输入框实例变量名为whitebutton,需要基于这个实例调用方法。
修复后的代码
from tkinter import * root = Tk() frame = Frame(root) frame.pack() def cancel(): quit() def upload(): # 调用输入框实例的get()方法获取内容 input_content = whitebutton.get() print(input_content) bottomframe = Frame(root) bottomframe.pack( side = BOTTOM ) whitebutton = Entry(frame, fg="black") whitebutton.pack( side = TOP) redbutton = Button(frame, text="Cancel", fg="red", command = cancel) redbutton.pack( side = LEFT) bluebutton = Button(frame, text="Upload URL", fg="blue", command = upload) bluebutton.pack( side = RIGHT ) root.mainloop()
额外优化建议
- 如果要避免输入内容为空时打印无效内容,可以增加判断逻辑:
if input_content.strip(): print(input_content) - 变量命名建议更有语义,比如把
whitebutton改成url_entry,后续维护代码时更容易理解含义
内容的提问来源于stack exchange,提问作者Kieran
相关产品推荐
相关产品推荐

