以下是一个使用Python的GUI库Tkinter创建按钮和实现无限循环的示例代码:
import tkinter as tk
def start_loop():
# 定义一个函数,用于实现无限循环
count = 0
while True:
print("循环次数:", count)
count += 1
def stop_loop():
# 定义一个函数,用于停止循环
print("停止循环")
def create_gui():
# 创建GUI窗口
window = tk.Tk()
# 创建开始按钮
start_button = tk.Button(window, text="开始循环", command=start_loop)
start_button.pack()
# 创建停止按钮
stop_button = tk.Button(window, text="停止循环", command=stop_loop)
stop_button.pack()
# 运行GUI主循环
window.mainloop()
# 调用函数创建GUI
create_gui()
这个示例代码创建了一个GUI窗口,其中包含两个按钮:“开始循环”按钮和“停止循环”按钮。当点击“开始循环”按钮时,会调用start_loop()
函数,进入一个无限循环,每次循环输出循环次数。当点击“停止循环”按钮时,会调用stop_loop()
函数,停止循环。整个程序通过create_gui()
函数创建GUI窗口并运行主循环。