Creating Tkinter Buttons To Stop/skip A 2d Loop
I am developing a tkinter GUI program which has the function of reading each single element in a 2D array. I need three buttons ('Start', 'Skip' and 'Stop') which have the followin
Solution 1:
Something like this might work for you
import tkinter as tk
x =0
y =0array= [[11,12,13,14],[21,22,23,24],[31,32,33,34],[41,42,43,44]]
running=True
def start():
global x, y, running
x = y =0running=True
output()
def skip():
global x, y
x +=1
y =0
def stop():
globalrunningrunning=False
def output():
global x, y, running
try:
print(array[x][y])
except IndexError as e:
if x >= len(array):
#Run outof lists
running=False
elif y >= len(array[x]):
y =0
x +=1else:
raise e
y +=1
if running:
root.after(1000, output)
root = tk.Tk()
btnStart = tk.Button(root,text="Start",command=start)
btnSkip = tk.Button(root,text="Skip",command=skip)
btnStop = tk.Button(root,text="Stop",command=stop)
btnStart.grid()
btnSkip.grid()
btnStop.grid()
root.mainloop()
I'm keeping track of the index in to the array for both dimensions using x
and y
. When I try to print the next item, if we've reached the end of the current array, the IndexError exception will be thrown which we then handle to increment on to the next row. When we reach 44, we are at the end of the list and running
is set to false.
Solution 2:
You could use a Thread.
import threading
array = [1,2,3,4,5,6]
running == Falsedefdo_print():
count = 0while running == True:
print(array[count])
count += 1defstop():
running = False
x = threading.Thread(target=do_print)
y = threading.Thread(target=stop)
btnStart = tk.Button(root,text="Start",command=x.start)
btnStop = tk.Button(root,text="Stop",command=y.start)
This is just an exemple with a 1 dimesion array.
Post a Comment for "Creating Tkinter Buttons To Stop/skip A 2d Loop"