繁体   English   中英

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

[英]Tkinter entry widget .get doesn't work

我是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()

当我在输入小部件中键入字符串并按Enter键时,什么也没有发生。 就像我说的那样,我不是很有经验,这是我的第一个项目,但是在阅读了有关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()在最后。

而你要删除tkintertkinter.Button

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()了,它是一个字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM