1.这是我的代码,你可以在这里看到send((方法。我想在on_clossing((方法中使用UserQus和BotAns out of send方法来处理firebase数据库中的疼痛,我做不到,请给我解决方案。
# Creating GUI with tkinter
import tkinter
from tkinter import *
base = Tk()
# from firebase import firebase
UserQus = []
BotAns = []
# This method is for tkinter button
def send():
msg = EntryBox.get("1.0", 'end-1c').strip()
EntryBox.delete("0.0", END)
if msg != '':
ChatLog.config(state=NORMAL)
ChatLog.insert(END, "You: " + msg + 'nn')
ChatLog.config(foreground="#442265", font=("Verdana", 14))
res = chatbot_response(msg)
ChatLog.insert(END, "Bot: " + res + 'nn')
ChatLog.config(state=DISABLED)
ChatLog.yview(END)
# here msg an res are append in UserQus and BotAns
UserQus.append(msg)
BotAns.append(res)
def on_closing():
from firebase import firebase
firebase = firebase.FirebaseApplication('https://fir-demopython.firebaseio.com/', None)
# here UserQus and BotAns are sore in data variable for define in firebase.post() # that store in database
data = {'You': UserQus, 'Bot': BotAns}
res = firebase.post('fir-demopython/DemoTbl', data)
if messagebox.askokcancel("Quit", "Do you want to quit?"):
base.destroy()
非常简单:您在send()
函数中定义on_closing()
函数。这意味着1/每次调用send
时都会重新创建,2/它只在send
函数中可见(它是一个局部变量(。
只需将您的on_closing()
定义移到send()
函数的之外(并将导入移到顶级(,问题就解决了:
# imports should NOT be in functions
from firebase import firebase
def send():
msg = EntryBox.get("1.0", 'end-1c').strip()
EntryBox.delete("0.0", END)
if msg != '':
ChatLog.config(state=NORMAL)
ChatLog.insert(END, "You: " + msg + 'nn')
ChatLog.config(foreground="#442265", font=("Verdana", 12))
res = chatbot_response(msg)
ChatLog.insert(END, "Bot: " + res + 'nn')
ChatLog.config(state=DISABLED)
ChatLog.yview(END)
UserQus.append(msg)
BotAns.append(res)
# and this should not be defined within the `send()` function, of course
def on_closing():
firebase = firebase.FirebaseApplication('https://fir-demopython.firebaseio.com/', None)
data = {'You': UserQus, 'Bot': BotAns}
res = firebase.post('fir-demopython/DemoTbl', data)
if messagebox.askokcancel("Quit", "Do you want to quit?"):
base.destroy()