我正在尝试使用Entry小部件(用于用户输入)和Text小部件(用于输出)在Tkinter中创建聊天程序。该程序首先在“文本”小部件中插入一个问题,如果用户回答“是”(通过按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)
答案 0 :(得分:0)
可能不是最干净的方法,但是可以将生成器与经过修改的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()
答案 1 :(得分:0)