python - 创建 Tkinter 按钮以停止/跳过 2D 循环
问题描述
我正在开发一个 tkinter GUI 程序,它具有读取二维数组中每个元素的功能。我需要三个按钮(“开始”、“跳过”和“停止”),它们具有以下功能:
“开始”按钮让程序一一读取并打印数组内的元素。例如,在下面的代码中,它首先打印“11”,然后是“12”,然后是“13”,然后是“14”,然后是“21”,依此类推,直到完成整个数组。
“跳过”按钮允许程序跳过程序正在读取的行。例如,当程序正在打印“12”时,如果我单击“跳过”按钮,它将跳转到第二行并开始打印“21”。
“停止”按钮停止和整个程序。
目前,我可以按照以下示例管理一维循环案例:[TKinter - 如何使用停止按钮停止循环?][1]。然而,二维循环仍然是一个巨大的挑战。有没有人有经验?非常感谢!
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()
解决方案
像这样的东西可能对你有用
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。
推荐阅读
- css - 如何在反应组件上添加多个类名
- performance - Http Range 请求将视频从 url 流式传输到 exoplayer
- laravel - 如何使用id从数据库中获取数据?
- intellij-idea - Intellij IDEA 很慢,编译很慢而且很耗内存
- xquery - 如何使用marklogic获取xml中的项目数
- uitableview - 问题从具有多个部分的表中删除单行(Swift 4)
- c# - Windows 上的 MeasureString 与 .NET Core 中的 Ubuntu 不匹配
- amazon-web-services - 如何从 Amazon Connect 中的 amazon lex 响应访问 sessionAttributes 值?
- c - C:在 C 中执行和输出 shell 命令
- android - 如何以编程方式将 setStateListAnimator 用于我的复选框?