File tree 1 file changed +71
-0
lines changed
tkinter/progressbar/progressbar-threading-global-variable
1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ # author: Bartlomiej "furas" Burek (https://blog.furas.pl)
3
+ # date: 2021.07.30
4
+ #
5
+ # title: Initializing tkinter gui leads to main thread not in main loop
6
+ # url: https://stackoverflow.com/questions/68577245/initializing-tkinter-gui-leads-to-main-thread-not-in-main-loop/
7
+
8
+ import threading
9
+ import time
10
+ import tkinter as tk
11
+ import tkinter .ttk as ttk
12
+
13
+ # --- functions ---
14
+
15
+ def long_script ():
16
+ global progress_value
17
+
18
+ for i in range (20 ):
19
+ print ('loop:' , i )
20
+
21
+ # update global variable
22
+ progress_value += 5
23
+
24
+ time .sleep (.5 )
25
+
26
+ def run_long_script ():
27
+ global progress_value
28
+ global t
29
+
30
+ if t is None : # run only one thread
31
+ # set start value
32
+ progress_value = 0
33
+ # start updating progressbar
34
+ update_progressbar ()
35
+ # start thread
36
+ t = threading .Thread (target = long_script )
37
+ t .start ()
38
+ else :
39
+ print ('Already running' )
40
+
41
+ def update_progressbar ():
42
+ global t
43
+
44
+ # update progressbar
45
+ pb ['value' ] = progress_value
46
+
47
+ if progress_value < 100 :
48
+ # run it again after 100ms
49
+ root .after (100 , update_progressbar )
50
+ else :
51
+ # set None to run again
52
+ t = None
53
+
54
+ # --- main ---
55
+
56
+ # default value at start
57
+ progress_value = 0
58
+ t = None
59
+
60
+ # - gui -
61
+
62
+ root = tk .Tk ()
63
+
64
+ pb = ttk .Progressbar (root , mode = "determinate" )
65
+ pb .pack ()
66
+
67
+ b = tk .Button (root , text = "start" , command = run_long_script )
68
+ b .pack ()
69
+
70
+ root .mainloop ()
71
+
You can’t perform that action at this time.
0 commit comments