Tkinter entry widget .get 不起作用



我对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谢谢。

您的代码缺少对mainloop()的调用。您可以尝试将它添加到drawStatWindow()函数的末尾:

statWindow.mainloop()

你可能想把你的代码重构成一个类。这允许你避免使用全局变量,并且通常为你的应用程序提供更好的组织:

from tkinter import *
class App:
    def __init__(self, statWindow):
        statWindow.title("View Statistics")
        statWindow.config(bg = "grey")
        statWindow.geometry('800x900')
        self.searched = StringVar()
        searchBox = Entry(statWindow, textvariable=self.searched)
        searchBox.place(x= 450, y=50, width = 200, height = 24)
        enterButton = Button(statWindow, text ="Enter", command=self.searchButton)
        enterButton.config(height = 1, width = 4)
        enterButton.place(x=652, y=50)
    def searchButton(self):
        text = self.searched.get()
        print(text)

root = Tk()
app = App(root)
root.mainloop()

您必须添加mainloop(),因为tkinter需要它来运行。

如果你在IDLE中运行使用tkinter的代码,那么IDLE运行自己的mainloop(),代码可以工作,但通常你必须在最后添加mainloop()

并且你必须删除tkinter.Button中的tkinter

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)
    # remove `tkinter` in `tkinter.Button`
    enterButton = Button(statWindow, text="Enter", command=searchButton)
    enterButton.config(height=1, width=4)
    enterButton.place(x=652, y=50)
    # add `mainloop()`
    statWindow.mainloop()
drawStatWindow()

不需要使用textvariable,你应该使用这个:

searchBox = Entry(statWindow)
searchBox.focus_set()
searchBox.place(x= 450, y=50, width = 200, height = 24)

那么你将能够使用searchBox.get(),这将是一个字符串

最新更新