How to get text from Entry widget

后端 未结 1 889
醉酒成梦
醉酒成梦 2020-12-22 13:41

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 o

相关标签:
1条回答
  • 2020-12-22 13:53

    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()
    
    0 讨论(0)
提交回复
热议问题