Я хочу получить доступ к UserQus.append (msg) и BotAns.append (res) из метода send () в python - PullRequest
0 голосов
/ 18 февраля 2020

1. Это мой код, здесь вы можете увидеть метод send (). Я хочу использовать UserQus и BotAns из метода send в методе on_closing () для болячки в базе данных 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 + '\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()

1 Ответ

0 голосов
/ 18 февраля 2020

Проще говоря: вы определяете функцию on_closing() в функции send(). Это означает, что 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()
...