python - 单击按钮后如何继续循环?
问题描述
我试图暂停一个循环,然后在按下按钮后继续循环。我有一个 for 循环,它从列表中获取问题,然后将其显示给用户回答,然后在用户回答时继续
用户单击下一步按钮后如何继续。这是我下面的代码
from tkinter import *
class exam:
global nexq
def __init__(self,master):
self.master = master
self.master.title("tuples inside Lists")
self.master.geometry("300x300+0+0")
self.master.resizable(False,False)
self.panel = Frame(self.master,width=300,height=300,bg="brown")
self.panel.pack_propagate(0)
self.panel.pack(fill="both")
self.ans = IntVar()
self.board = Text(self.panel, width=40,height=10)
self.board.grid(rowspan=2,columnspan=3 )
self.opt1 = Radiobutton(self.panel,text="Nigeria",variable=self.ans,value=1,command=self.startexam)
self.opt1.grid(row=5,column=0,sticky=W)
self.opt2 = Radiobutton(self.panel,text="Ghana",variable=self.ans,value=2)
self.opt2.grid(row=5,column=2,sticky=W)
self.btnnext = Button(self.panel,text="next",command=self.nextq)
self.btnnext.grid(row=20,column=0,sticky=W)
def startexam(self):
global nexq
nexq = False
self.ans.set(0)
self.qstns = [('what is your name','john','philip','john'),
('where do you stay','Abuja','lagos','lagos'),
('what can you do','sing','program','program')]
for qustn,optn1,optn2,ans in self.qstns:
self.board.delete('1.0',END)
self.board.insert(END,qustn)
self.opt1.configure(text=optn1)
self.opt2.configure(text=optn2)
if not nexq:
break
else:
continue
def nextq(self):
global nexq
nexq = True
return True
解决方案
正如 Reblochon 所提到的,您可以使用生成器通过使用yield
. 要了解其工作原理,我强烈建议您在此处yield
阅读 SO 上投票率最高的 Python 帖子。
以下是使用您的问题作为数据的最小示例:
import tkinter as tk
root = tk.Tk()
q = tk.Label(root,text="Question")
b = tk.Spinbox(root)
q.pack()
b.pack()
def ask_question():
qstns = [('what is your name','john','philip','john'),
('where do you stay','Abuja','lagos','lagos'),
('what can you do','sing','program','program')]
for i in qstns:
yield i[0], i[1:]
a = ask_question()
def get_next():
try:
start.config(text="Next question")
question, answer = next(a)
q.config(text=question)
b["value"] = answer
except StopIteration:
start.config(text="No more questions!",state="disabled",relief="sunken")
start = tk.Button(root,text="Start",command=get_next)
start.pack()
root.mainloop()
推荐阅读
- ios - 我正在尝试使用图像幻灯片放映 cocoapods,页面指示器仅在我的项目中无法正常工作,但在演示和新项目中运行良好
- javascript - 如何在不触发“window.onunload”的情况下关闭窗口?
- node.js - 如何使用异步函数修复“意外令牌”错误
- java - 如果改造多个调用返回您需要的内容,如何只通知用户一次?
- hadoop - 将字符串与 hdfs 命令相结合
- php - 哪个是最佳实践?身份类型或设置动态属性运行时?
- c# - C# WPF MVVM Controlling mediaplayer position with slider makes audio stutter
- amazon-web-services - 在 AWS 中的现有图像上编写自定义文本
- ssl - OpenLDAP 不验证 TLS 证书
- c - 包含结构的自由链表包含结构