How to get text from Entry widget

早过忘川 提交于 2019-11-28 12:57:05

问题


I've looked at several posts on stackOverflow that explain the answer but no matter which I use, I never can get the string from my entry widget; it just detects a string of ""

here's my code:

def buttonTest():
    global score
    gui.title("Test")
    for child in gui.winfo_children():
        child.destroy()
    global questionText
    global questionAnswer
    questionText = StringVar()
    questionAnswer = 0    
    question = Label(gui, textvariable = questionText, fg = "black", bg = "white")
    question.grid(row = 0, column = 1)
    userInput = StringVar()
    input = Entry(gui, textvariable = userInput)
    input.grid(row = 1, column = 0)

swapQuestion()

checkAns = Button(text = "Check answer", command = partial(checkAnswer, userInput.get(), questionAnswer), fg = "black", width=10)
checkAns.grid(row = 1, column = 2)

回答1:


Please read and follow this SO help page. Your code is missing lines needed to run and has lines that are extraneous to your question. It is also missing indentation.

Your problem is that you call userInput.get() just once, while creating the button, before the user can enter anything. At that time, its value is indeed ''. You must call it within the button command function, which is called each time the button is pressed.

Here is a minimal complete example that both runs and works.

import tkinter as tk

root = tk.Tk()

user_input = tk.StringVar(root)
answer = 3

def verify():
    print(int(user_input.get()) == answer)  # calling get() here!

entry = tk.Entry(root, textvariable=user_input)
entry.pack()
check = tk.Button(root, text='check 3', command=verify)
check.pack()

root.mainloop()


来源:https://stackoverflow.com/questions/28947795/how-to-get-text-from-entry-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!