我已经设法从输入字段中获取user_input,以便在按下 Enter 键时显示在我的文本小部件上,但是当我尝试使用用户输入的最后一个答案构建嵌套的 if/语句时,它似乎无法识别它并停止。
root = Tk()
...
Text and Entry widgets created
...
def Enter_pressed(event):
global input_get
input_get = input_field.get()
print(input_get)
messages.tag_config("right", justify="right")
messages.insert(INSERT, '%sn' % input_get, "right")
input_user.set('')
return "continue"
frame = Frame(root)
input_field.bind("<Return>", Enter_pressed)
frame.pack()
def question():
question1 = str(">>>Do you like apples?")
messages.insert(INSERT, '%sn' % question1)
if input_get == str("Yes") or input_get == str("yes"):
messages.insert(INSERT, ">>>Great")
else:
question2 = str(">>>How about peaches?")
messages.insert(INSERT, '%sn' % question2)
if input_get == str("Yes") or input_get == str("yes"):
messages.insert(INSERT, ">>>I like peaches too.")
else:
messages.insert(INSERT, ">>Have you tried mango?")
messages.after(5000, question)
root.mainloop()
我正试图向 oo 方法传福音......所以看看下面的脚本
import tkinter as tk
class App(tk.Frame):
def __init__(self,):
super().__init__()
self.master.title("Hello World")
self.option =tk.IntVar()
self.option.set(2)
self.questions = {0:"Do you like apples?",
1:"How about peaches?",
2:"I like peaches too.",
3:"Have you tried mango?",
4:"Great",
5:"End of the questions."}
self.which = tk.IntVar()
self.which.set(0)
self.init_ui()
def init_ui(self):
self.pack(fill=tk.BOTH, expand=1,)
f = tk.Frame()
self.question = tk.Label(f, text = self.questions[0])
self.question.pack()
ops = ('Yes','No',)
for index, text in enumerate(ops):
tk.Radiobutton(f,
text=text,
variable=self.option,
command=self.callback,
value=index,).pack(anchor=tk.W)
w = tk.Frame()
tk.Button(w, text="Print", command=self.callback).pack()
tk.Button(w, text="Reset", command=self.on_reset).pack()
tk.Button(w, text="Close", command=self.on_close).pack()
f.pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=0)
def callback(self):
#print(self.option.get())
if self.which.get()==0:
if self.option.get() == 0:
self.which.set(4)
else:
self.which.set(1)
elif self.which.get()==1:
if self.option.get() == 0:
self.which.set(2)
else:
self.which.set(3)
else:
self.which.set(5)
a = self.questions[self.which.get()]
self.question.config(text=a)
self.option.set(2)
def on_reset(self):
self.which.set(0)
self.option.set(2)
a = self.questions[self.which.get()]
self.question.config(text=a)
def on_close(self):
self.master.destroy()
if __name__ == '__main__':
app = App()
app.mainloop()
感谢您抽出宝贵时间回复。我尝试了你的选择,但我无法以某种方式让它工作。
我尝试在def Enter_presssed(event(代码块中插入嵌套的if语句,并且它在一定程度上起作用。它识别第一个"如果"和最后一个"else",但不识别介于两者之间的ifs和else。
在按下 Return 作为"文本"小部件中显示的最后一个问题的答案后,程序不应该查看和使用每个新input_get吗?