如何使用插入在文本小部件中的特定问题并检查用户是否回答是或否?

时间:2019-04-12 07:35:32

标签: python tkinter

我正在尝试使用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)

2 个答案:

答案 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)

使用面向对象的方法最简单。参见下文,如果您回答“是”,则脚本会加载另一个问题,无论如何它会写出所有答案...和一个响应...;)

Client.map()

enter image description here