在 Tkinter 中使用相同按钮的启动和停止功能 [英] Use start and stop function with same button in Tkinter

查看:41
本文介绍了在 Tkinter 中使用相同按钮的启动和停止功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在命令按钮的帮助下,我可以在 Tkinter 中断开框架的连接.但是有什么方法可以帮助使用相同的按钮启动吗?

With the help of the command button, I am able to disconnect the frame in Tkinter. But is there any way which helps to use the same button to start also?

import tkinter as tk
counter = 0
def counter_label(label):
  def count():
    global counter
    counter+=1
    label.config(text=counter)
    label.after(1000, count)
  count()


root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()

建议将不胜感激

推荐答案

这段代码过于复杂(我的回答),我建议改进它.但它展示了如何使用相同的按钮开始和停止以及保留大部分代码.

This code is overly complicated (my answer), I suggest improving it. But it shows how one could use the same button for both start and stop as well as keeping most of your code.

import tkinter as tk

def counter_label(label):
    a = 0
    label.config(text=str(a))
    def count():
        nonlocal a
        label.config(text=str(a))
        a += 1
        label.after(1000, count)
    return count

def start_stop(root, btn_text, counter):
    first = True
    def call():
        nonlocal first
        if first:
            counter()
            first = False
            btn_text.set('Stop')
        else:
            root.destroy()
    return call

root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter = counter_label(label)
btn_text = tk.StringVar()
button = tk.Button(root, textvariable=btn_text, width=25, command=start_stop(root, btn_text, counter))
btn_text.set('Start')
button.pack()
root.mainloop()

这篇关于在 Tkinter 中使用相同按钮的启动和停止功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆