如何在Python Tkinter中点击按钮依次存储姓名与姓氏至不同变量
实现分步获取姓名并输出问候的聊天机器人修改方案
你需要添加状态跟踪逻辑来区分首次和第二次输入,同时处理输入内容的冗余换行,以下是修改后的完整代码:
from tkinter import * import sys root = Tk() root.title("Chat Bot") root.geometry("400x500") root.resizable(width=FALSE, height=FALSE) chatWindow = Text(root, bd=1, bg="black", width="50", height="8", font=("Arial", 12), foreground="#00ffff") chatWindow.place(x=6,y=6, height=385, width=370) messageWindow = Text(root, bd=0, bg="black",width="30", height="4", font=("Arial", 23), foreground="#00ffff") messageWindow.place(x=128, y=400, height=88, width=260) # 初始化状态变量:0=等待输入名字,1=等待输入姓氏,2=完成输入 input_step = 0 name = "" lastname = "" def get(): global input_step, name, lastname # 获取输入并去除首尾空白(包括Text控件自带的换行符) user_input = messageWindow.get('1.0', END).strip() messageWindow.delete('1.0', END) if not user_input: return # 忽略空输入 if input_step == 0: name = user_input print(f"Hi {name}! Now please enter your last name.\n") input_step = 1 elif input_step == 1: lastname = user_input print(f"Hello {name} {lastname}! Nice to meet you.\n") input_step = 2 # 切换状态避免重复触发 Button= Button(root, text="Send", command=get, width="12", height=5, bd=0, bg="#0080ff", activebackground="#00bfff",foreground='#ffffff',font=("Arial", 12)) Button.place(x=6, y=400, height=88) def redirector(inputStr): chatWindow.insert(INSERT, inputStr) sys.stdout.write = redirector print("Hello, I am your awesome assistant today.\n") print("Please enter your first name.\n") root.mainloop()
关键修改说明:
- 新增
input_step变量跟踪当前输入阶段,明确区分"获取名字""获取姓氏""完成"三个状态 - 使用
global关键字在函数内访问全局变量,确保输入内容能被正确存储 - 对用户输入执行
strip()处理,去掉Text控件自带的换行符和首尾无效空格 - 优化交互提示语,让用户清晰知道当前需要输入的内容
- 添加空输入判断,避免无内容点击Send按钮导致的无效操作
内容的提问来源于stack exchange,提问作者Fras
相关产品推荐
相关产品推荐

