我试图制作一个可以暂停和恢复循环的按钮。
在代码中:
for index in range(10):
print index
// Runs until here, and pause
// Button pressed
print index + 10
// Runs until here, and pause
// Button pressed
在终端:
0
// Button pressed
10
// Button pressed
1
// Button pressed
11
...
9
// Button pressed
19
// Button pressed
有没有办法可以暂停并使用按钮恢复循环?
答案 0 :(得分:1)
您可以通过在每次点击按钮时调用next()
来使用生成器。
一个小例子:
import tkinter as tk
def plusten(x):
i = 0
while i<x:
yield i
yield i+10
i += 1
def next_item():
if gen:
try:
lbl["text"] = next(gen) #calls the next item of generator
except StopIteration:
lbl["text"] = "End of iteration" #if generator is exhausted, write an error
else:
lbl["text"] = "start loop by entering a number and pressing start loop button"
def start_gen():
global gen
try:
gen = plusten(int(ent.get()))
lbl["text"] = "loop started with value: " + ent.get()
except ValueError:
lbl["text"] = "Enter a valid value"
gen = None
root = tk.Tk()
ent = tk.Entry()
ent.pack()
tk.Button(root, text="start loop", command=start_gen).pack()
tk.Button(root, text="next item", command=next_item).pack()
lbl = tk.Label(root, text="")
lbl.pack()
root.mainloop()
答案 1 :(得分:0)
''' 在代码中导入以下内容 从tkinter导入* 导入时间
以下程序使用两个按钮创建一个tkinter窗口 (暂停和退出),同时打印数字序列 从1到numb(numb = 20,此处用于说明),且可控 两次打印之间的时间延迟(此处为2秒)。按下 暂停按钮停止打印,将按钮文本更改为“继续”。 片刻后,如果按下“继续”按钮,则继续打印。 要退出打印,请按退出按钮。 在图中,打印数字是象征性的。也可能是 显示具有时间延迟的图像。当需要查看 更详细的图像,显示该图像时可以暂停显示 并在需要查看剩余图像时恢复。 ''' 从tkinter导入* 导入时间
global move,stop
move = 1 #this a variable which can take a value 1 or 0
stop='Initial-Value' #This is a variable to control the for and while loops.
#Assignment of string as variable is optional. It could be
#integer as well
def switch(): #controls back and forth switching between Pause and Resume
global move
move = not move
def come_out(): # controls the process to be running or quit
global stop
stop='stop'
numb=20
root = Tk()
Pause_Button=Button(root,bg='wheat',command=switch)
Pause_Button.place(relwidth=0.25,relx=0.2,rely=0.2)
Quit_Button=Button(root,bg='lightblue',text='Quit',command=come_out)
Quit_Button.place(relwidth=0.25,relx=0.5,rely=0.2)
time.sleep(2)
for s in range(numb):
if stop=='stop':
break
stop='continue_while_loop'
while s<numb and stop=='continue_while_loop':
stop='enter_for_loop_again'
Pause_Button.update()
if move==1:
Pause_Button["text"]='Pause'
print('s2=',s,'\n')
time.sleep(2)
else:
stop='continue_while_loop'
Pause_Button["text"]='Resume'
Quit_Button.update()
root.mainloop()