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()
关键逻辑说明
输入
0的处理:- 用
os.system("python another_script.py")启动指定的外部Python文件(需替换为你的实际文件名) - 调用
root.destroy()直接关闭当前聊天窗口,结束对话
- 用
输入
01的处理:- 先插入告别语到聊天框
- 通过
root.after(2000, root.destroy)设置2秒延迟后关闭窗口,避免用户还没看到告别语就退出
细节优化:
- 添加输入框清空逻辑,提升交互体验
- 将多条件判断改为列表
in形式,简化代码结构 - 修正原代码拼写错误(
inconvenient改为inconvenience)
内容的提问来源于stack exchange,提问作者bon
相关产品推荐
相关产品推荐

