我想通过python中的send()方法访问UserQus.append(msg)和BotAns.append(res)

2024-10-01 17:38:36 发布

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

1.这是我的代码,您可以在这里看到send()方法。我想对firebase数据库中的sore使用UserQus和BotAns out of send方法on_closing()方法,我不能这样做,请给我解决方案

# 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 + '\n\n')
        ChatLog.config(foreground="#442265", font=("Verdana", 14))

        res = chatbot_response(msg)
        ChatLog.insert(END, "Bot: " + res + '\n\n')

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

Tags: 方法infromimportsendconfigtkinterres
1条回答
网友
1楼 · 发布于 2024-10-01 17:38:36

非常简单:您在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 + '\n\n')
        ChatLog.config(foreground="#442265", font=("Verdana", 12))

        res = chatbot_response(msg)
        ChatLog.insert(END, "Bot: " + res + '\n\n')

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

相关问题 更多 >

    热门问题