You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter GUI聊天机器人对话结束与跨文件跳转问题求助

Tkinter聊天机器人需求实现代码修改

待实现需求

  • 用户输入0时,结束当前对话并启动另一个Python文件
  • 用户输入01时,机器人发送告别语并关闭当前对话窗口

修改后的完整代码

import tkinter as tk
import os

root = tk.Tk()
root.title("Chatbot")

# 聊天文本框
txt = tk.Text(root)
txt.pack()

# 输入框
e = tk.Entry(root, width=50)
e.pack()

def send():
    send_msg = "You: " + e.get()
    txt.insert(tk.END, "\n" + send_msg)
    user_input = e.get().lower()
    e.delete(0, tk.END)  # 清空输入框

    if user_input in ["hello", "hi", "hey", "oi", "halo"]:
        txt.insert(tk.END, "\nRob: Hi there, how can I help you? \n 0.Contact seller directly \n 1.Order Tracking \n 2.Refund and Return \n 3.HELP \n Please enter a number.")
    
    elif user_input in ["whats your name?", "what is your name", "name", "you called", "what is your name?"]:
        txt.insert(tk.END, "\nRob: My name is Rob.")
    
    elif user_input == "0":
        # 启动另一个Python文件,替换为你的目标文件名
        os.system("python another_script.py")
        # 关闭当前窗口
        root.destroy()
    
    elif user_input == "1":
        txt.insert(tk.END, "\nRob: Your bag has arrived. \n 00. Homepage \n 01. Exit chat \n 0. Contact seller directly")
    
    elif user_input == "4":
        txt.insert(tk.END, "\nRob: Damage and Broken \n Sorry for the inconvenience. Please take a photo of your item and send it to seller as soon as possible. Thank you.\n 00. Homepage \n 01. Exit chat \n 0. Contact seller directly")
    
    elif user_input == "01":
        txt.insert(tk.END, "\nRob: Goodbye! Have a nice day!")
        # 延迟2秒关闭窗口,让用户看清告别语
        root.after(2000, root.destroy)

# 发送按钮
send_btn = tk.Button(root, text="Send", command=send)
send_btn.pack()

root.mainloop()

关键逻辑说明

  1. 输入0的处理:

    • 用os.system("python another_script.py")启动指定的外部Python文件(需替换为你的实际文件名)
    • 调用root.destroy()直接关闭当前聊天窗口,结束对话
  2. 输入01的处理:

    • 先插入告别语到聊天框
    • 通过root.after(2000, root.destroy)设置2秒延迟后关闭窗口,避免用户还没看到告别语就退出
  3. 细节优化:

    • 添加输入框清空逻辑,提升交互体验
    • 将多条件判断改为列表in形式,简化代码结构
    • 修正原代码拼写错误(inconvenient改为inconvenience)

内容的提问来源于stack exchange,提问作者bon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:35:25