首页 > 解决方案 > I am unable to fetch return value from a function in python

问题描述

In the code mentioned I am trying to get value of "text" which is inside the function . Outside of a function with one variable "A" but here I am not getting anything.Can anyone help me on this issue please

Also when I am writing print statement inside the function it is printing the value

enter code here

from tkinter import *
window = Tk()
window.geometry('500x500')
def callback(self):
    text = No_of_chances.get()
    return text
No_of_chances = Entry(window)
No_of_chances.place(x=50, y=300)
No_of_chances.bind('<Return>', callback)
A=text
print(A)

window.mainloop()

标签: python-3.xtkintertkinter-entry

解决方案


text尝试执行此操作时未定义该变量A=text,因为该函数callback()仅在按下 Enter 按钮时调用。因此text,当您尝试将其分配给时不存在A

Number_of_chances回调函数工作得非常好,它获取您拥有的条目中的当前字符串,并返回它。

话虽这么说,您的问题非常不清楚,因为您没有提供任何上下文来说明您想对Entry按 Enter 时获得的文本做什么,如果您提供一些上下文,我或其他人可能能够更好地帮助解决您的问题.

这是一个解决方案,因此 A 将包含您想要的值。

from tkinter import *

window = Tk()
window.geometry('500x500')
text = ""

def callback(event):
    text = No_of_chances.get()
    print(text)
    return text

No_of_chances = Entry(window)
No_of_chances.place(x=50, y=300)
No_of_chances.bind('<Return>', callback)
A=text
print(A)

window.mainloop()

推荐阅读