python - 如何使用文本小部件中插入的某个问题并检查用户是否回答是或否?
问题描述
我正在尝试在 Tkinter 中使用用于用户输入的 Entry 小部件和用于输出的 Text 小部件制作聊天程序。程序以在 Text 小部件中插入的问题开始,如果用户回答“是”(按 ReturnKey),则使用 Text.insert() 方法插入另一个问题。如何检查用户回答“是”插入了哪个问题,以保持对话畅通?
'''' #making the widgets''''
input_field = Entry(root)
chat = Text(root)
'''''
def intro():
chat.insert(INSERT, question1)
chat.after(1000, intro)
def Enter_pressed(event):
input_get = input_field
chat.insert(INSERT, '%s\n' % input_get, "right")
input_field.focus()
question2 =str(....)
question3 =str(...)
question4 =str(...)
if input_get == "yes":
if question1:
chat.insert(INSERT, question2)
elif question2:
chat.insert(INSERT, question3)
elif input_get == "no":
chat.insert(INSERT, question4)
input_field.bind("<Return>", Enter_pressed)
解决方案
可能不是最干净的方法,但您可以使用生成器和修改后的enter_pressed
函数:
import tkinter as tk
root = tk.Tk()
questions = ["Q1","Q2","Q3"] #first store the questions in a list
answers = {} #store question and answer pair
def enter_pressed(event):
if input_field.get().lower() == "yes":
print ("YES")
answers[i] = "yes" #append to answer dict
elif input_field.get().lower() == "no":
print ("NO")
answers[i] = "no" #append to answer dict
else:
print ("Wrong answer!")
input_field.delete(0, tk.END)
return
input_field.delete(0, tk.END)
try:
next(generator)
except StopIteration:
print ("No more questions!")
print (answers)
def generate_questions():
global i
for i in questions:
chat.insert(tk.END,i+"\n")
yield i
input_field = tk.Entry(root)
input_field.pack()
input_field.bind("<Return>",enter_pressed)
generator = generate_questions()
chat = tk.Text(root)
chat.pack()
next(generator)
root.mainloop()
推荐阅读
- vba - Microsoft Access VBA,compact n 修复,数据库损坏
- c++ - 无法在 docker 容器中打开目录运行代码
- reactjs - 如何避免 React Hook UseState 共享状态?
- mysql - 如何在 MySQL 中选择与 MAX 值列相关的 DATE
- android-studio - 如何将项目添加到文本保持操作的下拉菜单
- java - Creating dynamic query using jpa criteria
- c# - 如何在c#中使用字典来比较两个列表
- excel - 将多个单元格中的值添加到列表框并取回第一个选定的值
- bootstrap-4 - 有没有办法设置引导下拉菜单何时变为下拉菜单?
- google-maps - 为什么我无法在 Google Cloud 中点击“启用”来启用地图地理编码?