回答編集履歴
2
コード追加
test
CHANGED
@@ -3,6 +3,51 @@
|
|
3
3
|
|
4
4
|
こちらのQAが、参考になると思います。
|
5
5
|
https://stackoverflow.com/questions/64282319/stop-button-for-breaking-while-loop-within-ipywidgets-ecosystem
|
6
|
+
|
7
|
+
```python
|
8
|
+
import time
|
9
|
+
import ipywidgets as widgets
|
10
|
+
|
11
|
+
from IPython.display import display
|
12
|
+
import threading
|
13
|
+
|
14
|
+
current = '-1'
|
15
|
+
flag = False
|
16
|
+
|
17
|
+
def loop_start(e):
|
18
|
+
with output:
|
19
|
+
print('Start')
|
20
|
+
thread.start()
|
21
|
+
|
22
|
+
def count_loop():
|
23
|
+
global current
|
24
|
+
for i in range(10):
|
25
|
+
with output:
|
26
|
+
print(current)
|
27
|
+
if flag:
|
28
|
+
return
|
29
|
+
time.sleep(1)
|
30
|
+
current = str(i)
|
31
|
+
|
32
|
+
def loop_stop(e):
|
33
|
+
global flag
|
34
|
+
flag = True
|
35
|
+
thread.join()
|
36
|
+
with output:
|
37
|
+
print('Stop')
|
38
|
+
|
39
|
+
output = widgets.Output()
|
40
|
+
start = widgets.Button(description='開始')
|
41
|
+
stop = widgets.Button(description='停止')
|
42
|
+
buttons = widgets.Box([start, stop])
|
43
|
+
|
44
|
+
start.on_click(loop_start)
|
45
|
+
stop.on_click(loop_stop)
|
46
|
+
|
47
|
+
display(buttons, output)
|
48
|
+
|
49
|
+
thread = threading.Thread(target=count_loop)
|
50
|
+
```
|
6
51
|
|
7
52
|
### 最初の回答
|
8
53
|
`loop_stop`の中の `flag` はglobalにしないといけないです。
|
1
追記
test
CHANGED
@@ -1,3 +1,10 @@
|
|
1
|
+
下記の変更だけではだめで、ちゃんとやるなら非同期処理を書いてやる必要があるみたいですね。
|
2
|
+
https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Asynchronous.html
|
3
|
+
|
4
|
+
こちらのQAが、参考になると思います。
|
5
|
+
https://stackoverflow.com/questions/64282319/stop-button-for-breaking-while-loop-within-ipywidgets-ecosystem
|
6
|
+
|
7
|
+
### 最初の回答
|
1
8
|
`loop_stop`の中の `flag` はglobalにしないといけないです。
|
2
9
|
じゃないと、flag というローカル変数を True でセットするだけになります。
|
3
10
|
```python
|
@@ -5,5 +12,4 @@
|
|
5
12
|
global flag
|
6
13
|
print('Stop')
|
7
14
|
flag = True
|
8
|
-
|
9
15
|
```
|