【问题标题】:A better way to do this in Tkinter?在 Tkinter 中执行此操作的更好方法?
【发布时间】:2020-10-27 21:06:46
【问题描述】:

我目前正在编写一个 Python Tkinter 开始和停止按钮。

当我点击开始时它使用tkinter,停止按钮应该出现在它的位置。但要做到这一点,我需要在按钮上使用.destroy()。所以为了解决这个问题,我做了以下事情(见代码打击);但是它看起来很笨重,不能不觉得我把它复杂化了。任何建议都会很棒

    def stop():
        global start_button

        try:
            stop_button.destroy()
        except NameError:
            pass

        print("Stopped. Hit GO to go again!")
        start_button = Button(self.b, text="GO!", font="calibri, 18", command=started, fg="white", width=10)
        start_button.pack(side=BOTTOM)
        start_button.config(bg="green")

    def started():
        global stop_button

        try:
            start_button.destroy()
        except NameError:
            pass

        print("Started. Hit ENTER to Stop!")
        stop_button = Button(self.b, text="STOP!", font="calibri, 18", command=stop, fg="white", width=10)
        stop_button.pack(side=BOTTOM)
        stop_button.config(bg="red")

    def first_start():
        start.destroy()
        started()

    start = Button(self.b, text="START!", font="calibri, 18", command=first_start, fg="white", width=10)
    start.pack(side=BOTTOM)
    start.config(bg="green")

【问题讨论】:

  • 为什么不保留按钮,而是更改名称和命令?
  • 我该怎么做?
  • Here 是一个主题非常相似的问题。基本上,您使用 configure 方法就像您已经使用的那样,但也可以使用它配置名称和命令。我会将其标记为重复
  • 你为什么不直接更改按钮的属性(例如文本、bg 等)而不是使用configure()

标签: python tkinter


【解决方案1】:

这是一个极简的开始/停止按钮,单击时可切换其外观和行为。使用这种切换机制无需销毁和替换按钮。

import tkinter as tk


def do_the_start_things():
    # replace print with the things to do at start
    print('starting now')
    
def do_the_stop_things():
    # replace print with the things to do at stop
    print('stopped!')

def toggle_start_stop():
    if startstop['text'] == 'START':
        startstop.config(text='STOP', fg='red')
        do_the_start_things()
    else:
        startstop.config(text='START', fg='green')
        do_the_stop_things()

        
root = tk.Tk()
startstop = tk.Button(root, text='START', command=toggle_start_stop, fg='green')
startstop.pack()


root.mainloop()

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    相关资源
    最近更新 更多