开发者

Accepting inputs from Tkinter

开发者 https://www.devze.com 2023-03-26 12:32 出处:网络
I want to write a GUI in Tkinter that accepts a text inputs from the user and stores it in a variable Text; I also want to be able to use this variable later on... Here is s开发者_如何学运维omething i

I want to write a GUI in Tkinter that accepts a text inputs from the user and stores it in a variable Text; I also want to be able to use this variable later on... Here is s开发者_如何学运维omething i tried that failed:

from Tkinter import *


def recieve():
    text = E1.get()
    return text

top = Tk()
L1 = Label(top, text="User Name")
L1.pack(side=LEFT)
E1 = Entry(top, bd=5)

E1.pack(side=RIGHT)

b = Button(top, text="get", width=10, command=recieve)
b.pack()

print text

top.mainloop()

So how do I do this?


The problem lies here:

print text    
top.mainloop()

Before top.mainloop() is called, text has not been defined. Only after the call to top.mainloop is the user presented with the GUI interface, and the mainloop probably loops many many times before the user gets around to typing in the Entry box and pressing the Button. Only after the button is pressed is recieve (sic) called, and although it returns a value, that value is not stored anywhere after recieve ends. If you want to print text, you have to do it in the recieve function:

from Tkinter import *

def receive():
    text = E1.get()
    print(text)
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
b = Button(top, text="get", width=10, command=receive)
b.pack()
top.mainloop()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号