嗨,我希望能够将用户输入文本作为变量存储,以便在Python中的定义之外使用。但我似乎只能访问定义本身中的变量。有什么办法让它在外面方便使用吗?在
import tkinter
#Quit Window when ESC Pressed
def quit(event=None):
window.destroy()
def GetCountry():
global InputCountry
InputCountry = UserInput.get()
#Create Main Window
window=tkinter.Tk()
window.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
window.title("Select Country to Analyze")
window.bind('<Escape>', quit)
UserInput = tkinter.Entry(window)
UserInput.pack()
ButtonClick = tkinter.Button(window, text='Enter', command=GetCountry)
ButtonClick.pack(side='bottom')
print(InputCountry)
window.mainloop()
当我试图调用GetCountry或InputCountry时,它表示它们没有定义
未定义变量InputCountry,因为它只存在于def GetCountry():indent块的作用域中。对于GetCountry,它是一个函数,因此您需要编写这个函数,它应该可以工作:
希望有帮助!在
print语句将不打印任何内容,即使它实际上被定义为在输入任何内容之前打印
UserInput
中输入的内容。删除以下无用行:并添加:
^{pr2}$在
def GetCountry():
的范围内。在另外,em>command无法返回函数。一种解决方法是将希望返回的值附加到方法对象本身。替换:
^{3}$有:
最终拥有:
相关问题 更多 >
编程相关推荐