如何在 Tkinter 中使用停止按钮停止循环?
考虑一个在循环中运行进程的情况,我们希望在单击按钮时停止循环。通常,在编程语言中,为了停止连续的while循环,我们使用break语句。但是,在 Tkinter 中,我们使用after()来代替while循环,从而在循环中运行定义的函数。要中断连续循环,可以使用一个全局布尔变量,该变量可以更新以更改循环的运行状态。
对于给定的示例,
创建一个类似于循环中标志的全局变量。
定义两个按钮,开始和停止,用于启动和停止执行。
定义两个函数,on_start()和on_stop(),用于向循环传递更新。
示例
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
running = True
# Define a function to print the text in a loop
def print_text():
if running:
print("Hello World")
win.after(1000, print_text)
# Define a function to start the loop
def on_start():
global running
running = True
# Define a function to stop the loop
def on_stop():
global running
running = False
canvas = Canvas(win, bg="skyblue3", width=600, height=60)
canvas.create_text(150, 10, text="Click the Start/Stop to execute the Code", font=('', 13))
canvas.pack()
# Add a Button to start/stop the loop
start = ttk.Button(win, text="Start", command=on_start)
start.pack(padx=10)
stop = ttk.Button(win, text="Stop", command=on_stop)
stop.pack(padx=10)
# Run a function to print text in window
win.after(1000, print_text)
win.mainloop()输出
运行以上代码以测试特定条件下的循环。
如果运行以上代码并单击“开始”按钮,则它将在循环中打印“Hello World”文本,可以通过单击“停止”按钮来停止。
Hello World Hello World Hello World Hello World Hello World Process finished with exit code 0
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP