Python Tkinter Entry get()

前端 未结 2 1584
抹茶落季
抹茶落季 2020-12-10 07:43

I\'m trying to use Tkinter\'s Entry widget. I can\'t get it to do something very basic: return the entered value.
Does anyone have any idea why such a simple script wou

相关标签:
2条回答
  • 2020-12-10 07:51

    Your first problem is that the call to get in entry = E1.get() happens even before your program starts, so clearly entry will point to some empty string.

    Your eventual second problem is that the text would anyhow be printed only after the mainloop finishes, i.e. you close the tkinter application.

    If you want to print the contents of your Entry widget while your program is running, you need to schedule a callback. For example, you can listen to the pressing of the <Return> key as follows

    import Tkinter as tk
    
    
    def on_change(e):
        print e.widget.get()
    
    root = tk.Tk()
    
    e = tk.Entry(root)
    e.pack()    
    # Calling on_change when you press the return key
    e.bind("<Return>", on_change)  
    
    root.mainloop()
    
    0 讨论(0)
  • 2020-12-10 08:17
    from tkinter import *
    import tkinter as tk
    root =tk.Tk()
    mystring =tk.StringVar(root)
    def getvalue():
        print(mystring.get())
    e1 = Entry(root,textvariable = mystring,width=100,fg="blue",bd=3,selectbackground='violet').pack()
    button1 = tk.Button(root, 
                    text='Submit', 
                    fg='White', 
                    bg= 'dark green',height = 1, width = 10,command=getvalue).pack()
    
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题