Python 在Tkinter有更好的方法吗?
我目前正在编写一个Python Tkinter启动和停止按钮 由于它使用了Python 在Tkinter有更好的方法吗?,python,tkinter,Python,Tkinter,我目前正在编写一个Python Tkinter启动和停止按钮 由于它使用了tkinter当我单击开始时,停止按钮应该出现在它的位置上。但要做到这一点,我需要在按钮上使用.destroy()。因此,为了解决这个问题,我做了以下工作(参见代码blow);然而,它看起来笨重,不能不觉得我已经把它复杂化了。任何建议都很好 def stop(): global start_button try: stop_button.destroy()
tkinter
当我单击开始时,停止按钮应该出现在它的位置上。但要做到这一点,我需要在按钮上使用.destroy()
。因此,为了解决这个问题,我做了以下工作(参见代码blow);然而,它看起来笨重,不能不觉得我已经把它复杂化了。任何建议都很好
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")
这是一个极简主义的开始/停止按钮,单击时可切换其外观和行为。没有必要用这种切换机制破坏和更换按钮
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()
这是一个极简主义的开始/停止按钮,单击时可切换其外观和行为。没有必要用这种切换机制破坏和更换按钮
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()
为什么不保留按钮,但更改名称和命令?我该怎么做?这是一个主题非常相似的问题。基本上,您可以像以前一样使用
configure
方法,但也可以使用它配置名称和命令。我会将此标记为重复。为什么不使用configure()
更改按钮的属性(如文本、背景等)。这是否回答了您的问题?为什么不保留按钮,但更改名称和命令?我该怎么做?这是一个主题非常相似的问题。基本上,您可以像以前一样使用configure
方法,但也可以使用它配置名称和命令。我会将此标记为重复。为什么不使用configure()
更改按钮的属性(如文本、背景等)。这是否回答了您的问题?