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

2024-06-26 00:01:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 用户文本定义tkinterdefwindowpackquit
2条回答

未定义变量InputCountry,因为它只存在于def GetCountry():indent块的作用域中。对于GetCountry,它是一个函数,因此您需要编写这个函数,它应该可以工作:

print(GetCountry())

希望有帮助!在

print语句将不打印任何内容,即使它实际上被定义为在输入任何内容之前打印UserInput中输入的内容。删除以下无用行:

print(GetCountry)
print(InputCountry)

并添加:

^{pr2}$

def GetCountry():的范围内。在

另外,em>command无法返回函数。一种解决方法是将希望返回的值附加到方法对象本身。替换:

^{3}$

有:

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()

相关问题 更多 >