2017-11-19 179 views
0

ループを一時停止して再開できるボタンを作成しようとしています。コードでPythonの一時停止/再開ボタン

:ターミナルで

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

。続行する前に、 'for'ループがボタンが押されるのを待つようにしますか? – James

+0

@Jamesはい、正確です。 –

+0

すべてのGUIフレームワークで長時間実行されるループは、メインループ(イベントループ)を停止し、ハングアップしているように見えるため問題になります。だから主な問題は、それを実行し、mainloopを停止しない方法です。 2番目のスレッドで実行する場合は 'while first_time_pressed == False:pass'を使用してループを止めることができ、メインスレッドのButtonは' first_time_pressed = True'、 'second_time_pressed = True'などを変更します。 'ループはCPUパワーを使いすぎます。 – furas

答えて

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() 
関連する問題