需要调用ini方法中的pre中的返回值true_ans
true_ans=pre()报错未解析的引用 'pre'
ans = "ABCDAAACDABCDABBCDABCDABCCDABCDABCDDABCDABCDAABCCC"
array = re.findall(r'.{5}', ans)
true_ans = pre()
arr = re.findall(r'.{5}', true_ans)
# input方法内嵌一个pre方法和一个子窗口控件
def ini():
# pre方法将子窗体win中获取的答案进行合并
def pre():
global true_ans
ans1 = entry_011.get()
ans2 = entry_012.get()
true_ans = ans1+ans2
# 判断输入字符是否为英文字母
if true_ans.isalpha():
if len(true_ans) == 50:
win.destroy()
return true_ans
else:
tk.messagebox.showinfo("警告", "答案有误\n请核对")
else:
tk.messagebox.showinfo("警告", "请正确输入答案")
win = tk.Toplevel(window) # 创建子窗口win位于主窗口window
win.title('答案输入')
win.geometry('390x280')
win.iconbitmap('')
win.resizable(False, False)
# 1~10
label_011 = tk.Label(win, text='1~5')
label_011.place(x=20, y=10)
entry_011 = tk.Entry(win)
entry_011.insert(0, array[0])
entry_011.place(x=22, y=30)
label_012 = tk.Label(win, text='6~10')
label_012.place(x=210, y=10)
entry_012 = tk.Entry(win)
entry_012.insert(0, array[1])
entry_012.place(x=212, y=30)
btn_pre = tk.Button(win, text='保存', command=pre)
btn_pre.place(x=270, y=230)
btn_out = tk.Button(win, text='退出', command=win.destroy)
btn_out.place(x=320, y=230)
Traceback (most recent call last):
File "E:\pythonProject1\1\window.py", line 9, in
true_ans = pre()
NameError: name 'pre' is not defined
试过在ini()最后加上
btn_pre = tk.Button(win, text='保存', command=pre)
btn_pre.place(x=270, y=230)
btn_out = tk.Button(win, text='退出', command=win.destroy)
btn_out.place(x=320, y=230)
true_ans = pre()
return true_ans
然后把前面
true_ans = pre()
改为
true_ans = ini()
相同报错未解析的引用 'ini'
Traceback (most recent call last):
File "E:\pythonProject1\1\window.py", line 9, in
true_ans = ini()
NameError: name 'ini' is not defined
想要在外部的true_ans能引用到pre()中返回的true_ans
如果一个函数需要在别的地方使用,那你就别把它定义成嵌套函数,拿到外面来定义
而如果这个函数的返回值始终不变,只需要执行一次,那你不要return,直接写进全局变量里,别的地方直接判断全局变量