首页 文章

Tkinter条目小部件.get不起作用

提问于
浏览
0

我是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 回答

  • 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()
    
  • 0

    您必须添加 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()
    
  • -2

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

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

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

相关问题