我是python的新手,目前正在开展一个学校项目,我的目标是创建一个可用于搜索数据文件的搜索栏,但是我很难让搜索栏正常工作 . 我正在使用tkinter条目小部件 . 当我调用.get()时,不打印条目小部件中的字符串 . 这是我的代码......
from tkinter import *
def searchButton():
text = searched.get()
print (text)
def drawStatWindow():
global searched
statWindow = Tk()
statWindow.title("View Statistics")
statWindow.config(bg = "grey")
statWindow.geometry('800x900')
searched = StringVar()
searchBox = Entry(statWindow, textvariable = searched)
searchBox.place(x= 450, y=50, width = 200, height = 24)
enterButton = tkinter.Button(statWindow, text ="Enter", command =searchButton)
enterButton.config(height = 1, width = 4)
enterButton.place(x=652, y=50)
drawStatWindow()
当我在条目小部件中键入一个字符串并按下回车按钮时,没有任何反应 . 就像我说我不是很有经验,这是我的第一个项目,但在阅读了关于tkinter入口小部件后,我无法理解为什么这不起作用 . 我正在使用python V3.4.0谢谢 .
3 回答
您的代码缺少对
mainloop()
的调用 . 您可以尝试将其添加到drawStatWindow()
函数的末尾:您可能希望将代码重组为类 . 这允许您避免使用全局变量,并且通常为您的应用程序提供更好的组织:
您必须添加
mainloop()
因为tkinter
需要它才能运行 .如果您在IDLE中运行使用
tkinter
的代码,那么IDLE运行自己的mainloop()
并且代码可以正常工作,但通常您必须在末尾添加mainloop()
.你必须删除
tkinter.Button
中的tkinter
.不需要使用textvariable,你应该使用这个:
那么你将能够使用searchBox.get(),这将是一个字符串 .