[英]How to continue a loop after a button has been clicked?
我試圖暫停循環,然后在按下按鈕后繼續循環。 我有一個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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.