这是我到目前为止尝试获取用户输入的内容:
master = Tk()
master.title('Title')
v = StringVar()
L1 = Label(master, text = 'Name')
L1.pack(side = LEFT)
E1 = Entry(master, textvariable = v, bd = 5)
E1.pack(side = RIGHT)
def userinput():
a = raw_input(v.get())
print a
b = Button(master, text = 'Submit', command = userinput)
b.pack(side = BOTTOM)
master.mainloop()
真正的问题是,如何将v.get()raw_input存储到函数外部的变量中? THX!
答案 0 :(得分:0)
您可以创建一个全局变量来保存输入:
inp = None
然后让你的函数更新该变量:
def userinput():
global inp
a = raw_input(v.get())
print a
inp = a
因此,您的代码将如下所示:
master = Tk()
master.title('Title')
v = StringVar()
# Variable to hold the input
inp = None
L1 = Label(master, text = 'Name')
L1.pack(side = LEFT)
E1 = Entry(master, textvariable = v, bd = 5)
E1.pack(side = RIGHT)
def userinput():
# Declare 'inp' to be global
global inp
a = raw_input(v.get())
print a
# Update the variable
inp = a
b = Button(master, text = 'Submit', command = userinput)
b.pack(side = BOTTOM)
master.mainloop()
在上面的代码中,inp
将始终是输入的新副本,您可以在代码中的其他位置使用。
然而,考虑使您的代码成为一个类可能是值得的。这样,您就可以拥有一个名为self.inp
的类属性,而您不必执行global inp
。
答案 1 :(得分:0)
正如其他人所说 - 使用globe
使用类
的示例from Tkinter import *
class MainWindow():
def __init__(self, master):
self.master = master
self.master.title('Title')
self.v = StringVar()
self.L1 = Label(self.master, text = 'Name')
self.L1.pack(side = LEFT)
self.E1 = Entry(self.master, textvariable = self.v, bd = 5)
self.E1.pack(side = RIGHT)
self.B1 = Button(self.master, text = 'Submit', command = self.userinput)
self.B1.pack(side = BOTTOM)
self.B2 = Button(self.master, text = 'Print', command = self.print_external_variable)
self.B2.pack(side = TOP)
#------------------
def userinput(self):
global external_variable
external_variable = raw_input(self.v.get())
#external_variable = self.v.get()
print "inside - userinput:", external_variable
#------------------
def print_external_variable(self):
# you don't need global if you don't change external_variable
print "inside - print:", external_variable
#----------------------------------------------------------------------
external_variable = '- none -'
print "before run:", external_variable
master = Tk()
MainWindow(master)
master.mainloop()
print "after run:", external_variable
答案 2 :(得分:-1)
只需返回用户输入
即可def userinput():
a = raw_input(v.get())
return a
然后当你打电话时,你可以通过以下方式实现:
myvar=userinput()
现在,myvar
包含用户输入的值。