Tkinter条目小部件。get没有

2024-09-28 05:19:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我在entry小部件中输入一个字符串并按下enter按钮时,什么都不会发生。 就像我说的,我不是很有经验,这是我的第一个项目,但是在阅读了tkinter条目小部件之后,我不明白为什么这不起作用。 我使用的是pythonv3.4.0 谢谢。在


Tags: 项目字符串textconfigget部件tkinterdef
3条回答

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

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

那么你就可以使用搜索框.get(),这将是一个字符串。在

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

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

你必须删除tkinter中的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()

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

statWindow.mainloop()

您可能需要将代码重新构造为一个类。这样可以避免使用全局变量,并为应用程序提供更好的组织:

^{pr2}$

相关问题 更多 >

    热门问题