首页 > 解决方案 > 如何使用文本小部件中插入的某个问题并检查用户是否回答是或否?

问题描述

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

标签: pythontkinter

解决方案


可能不是最干净的方法,但您可以使用生成器和修改后的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()

推荐阅读