我正在开发一个tkinter GUI程序,它具有读取2D数组中的每个元素的功能。我需要三个按钮(“开始”,“跳过”和“停止”),它们有以下功能:
"Start“按钮让程序逐个读取和打印数组中的元素。例如,在下面的代码中,它首先打印"11",然后是"12",然后是"13",然后是"14",然后是"21",依此类推,直到完成整个数组。
“跳过”按钮允许程序跳过程序正在读取的行。例如,当程序打印"12“时,如果我点击”跳过“按钮,它将跳到第二行并开始打印"21”。
“停止”按钮停止和整个程序。
目前,我可以按照这个例子来管理1D循环的情况: TKinter -如何使用停止按钮停止循环?然而,2D循环仍然是一个巨大的挑战。有谁有这样的经验吗?非常感谢!
import tkinter as tk
import time
#Initialize the Root
root= tk.Tk()
root.title("Real time print")
root.configure(background = "light blue")
root.geometry("500x420")
# The array to be printed
array = [[11,12,13,14],[21,22,23,24],[31,32,33,34],[41,42,43,44]]
# Define the function to print each element in the array
def do_print():
print("The element inside the array")
time.sleep(1)
return
#Define strat, skip and stop buttons
def start_button():
do_print()
return
start = tk.Button(root, text = "Start", font = ("calbiri",12),command = start_button)
start.place(x = 100, y=380)
def skip_button():
return
skip = tk.Button(root, text = "Skip", font = ("calbiri",12),command = skip_button)
skip.place(x = 160, y=380)
def stop_button():
return
stop = tk.Button(root, text = "Stop", font = ("calbiri",12),command = stop_button)
stop.place(x = 220, y=380)
root.mainloop()
发布于 2021-01-07 14:03:31
像这样的东西可能会对你有用
import tkinter as tk
x = 0
y = 0
array = [[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 = 0
running = True
output()
def skip():
global x, y
x +=1
y = 0
def stop():
global running
running = False
def output():
global x, y, running
try:
print(array[x][y])
except IndexError as e:
if x >= len(array):
#Run out of lists
running = False
elif y >= len(array[x]):
y = 0
x += 1
else:
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()
我使用x
和y
跟踪数组中两个维度的索引。当我尝试打印下一项时,如果我们已经到达当前数组的末尾,则将抛出IndexError异常,然后我们将处理该异常以递增到下一行。当我们到达44时,我们在列表的末尾,并且running
被设置为false。
发布于 2021-01-07 14:15:51
你可以使用线程。
import threading
array = [1,2,3,4,5,6]
running == False
def do_print():
count = 0
while running == True:
print(array[count])
count += 1
def stop():
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)
这只是一个一维数组的例子。
https://stackoverflow.com/questions/65613432
复制相似问题