簡體   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