将用户输入文本存储为python中的变量

问题描述 投票:-1回答:2

嗨,我希望能够将用户输入文本存储为变量,以便在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时,它表示它们没有被定义

python tkinter
2个回答
0
投票

未定义变量InputCountry,因为它仅存在于def GetCountry():indent块的范围内。至于GetCountry,它是一个函数,因此你需要编写它,它应该工作:

print(GetCountry())

希望能帮助到你!


0
投票

该打印语句即使实际定义也不会打印,因为它会输入在输入任何内容之前在UserInput中输入的内容。删除无用的行:

print(GetCountry)
print(InputCountry)

并添加:

print(InputCountry)

def GetCountry():的范围内。

此外,设置为命令回调的函数无法真正返回。一种解决方法是将想要返回的值附加到方法对象本身。更换:

return InputCountry

有:

GetCountry.value = InputCountry

终于要:

import tkinter

#Quit Window when ESC Pressed
def quit(event=None):
    window.destroy()

def GetCountry():
    InputCountry = UserInput.get()
    GetCountry.value = InputCountry
    print(InputCountry)


#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')
window.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.