有没有办法在每次点击时切换按钮的颜色(例如,它从白色开始,第一次点击它变成蓝色,下次点击它会变回白色,如果它第三次被点击它再次变为蓝色......并且以相同的模式开始)。
如果这是可能的,有没有办法让python记住按钮是前一个会话的颜色,并在下次启动时保持这种颜色?
对的,这是可能的。
此处,按下按钮时,文本颜色从红色切换为蓝色。
如果将按钮选项的关键字参数从fg
更改为bg
,则在某些系统(不在OSX上)上,您将更改背景颜色而不是文本颜色。如果你愿意,试试吧。
import tkinter as tk # <-- avoid star imports
def toggle_color(last=[0]): # <-- creates a closure to memoize the last value of the colors index used to toggle
colors = ['red', 'blue']
color = colors[last[0]]
last[0] = (last[0] + 1) % 2 # <-- ensure the index is 0 or 1 alternatively
btn.config(fg=color)
if __name__ == '__main__':
root = tk.Tk()
btn = tk.Button(root, text='toggle', fg='blue', command=toggle_color)
btn.pack()
root.mainloop()
与其他答案不同,我建议使用面向对象的方法。下面的示例使用tkinter Button类作为基础,但添加了on_color
和off_color
参数,以指定按钮打开/关闭时所需的颜色。
这样,您可以拥有任意数量的具有相似行为的按钮,但无需更改每个按钮的状态。此行为在类中定义。
on_color
和off_color
是可选参数,如果未指定,将分别默认为“绿色”和“红色”。
import tkinter as tk
def pressed():
print("Pressed")
class ToggleButton(tk.Button):
def __init__(self, master, **kw):
self.onColor = kw.pop('on_color','green')
self.offColor = kw.pop('off_color','red')
tk.Button.__init__(self,master=master,**kw)
self['bg'] = self.offColor
self.bind('<Button-1>',self.clicked)
self.state = 'off'
def clicked(self,event):
if self.state == 'off':
self.state = 'on'
self['bg'] = self.onColor
else:
self.state = 'off'
self['bg'] = self.offColor
root = tk.Tk()
btn = ToggleButton(root,text="Press Me", on_color='blue',off_color='yellow',command=pressed)
btn.grid()
btn2 = ToggleButton(root,text="Press Me",command=pressed)
btn2.grid()
root.mainloop()
为了记住每个按钮所处的状态,您需要在关闭时保存文件并在启动时再次打开它。在过去,我通过编写包含所有设置字典的JSON文件来完成此操作。要在应用程序关闭时执行某些操作,可以将函数调用绑定到窗口管理器的删除窗口方法
root.protocol("WM_DELETE_WINDOW", app.onClose)
当窗口关闭时,这将调用onClose
的app
方法。在此方法中,您只需收集按钮的各种状态并将其写入文件。例如
settings = {}
settings['btn2_state'] = btn2.state
with open('settings.json','w') as settings_file:
settings.write(json.dumps(settings))
当您再次使用类似的东西打开程序时,可以再次读回来
with open('settings.json','r') as settings_file:
settings = json.load(settings_file)
btn2.state = settings['btn2_state']
您可以在按下按钮时更改按钮的颜色。有几种方法可以做到这一点。我发布了一些片段。
这是一个代码:
from tkinter import * #for python2 Tkinter
global x
x = 0
root = Tk()
def b1c(): #this function will run on button press
global x
if x == 0:
b1["bg"] = "blue"
x += 1
elif x == 1:
b1["bg"] = "white"
x = 0
b1 = Button(root,text="Press me to change the color",command = b1c) #making button
if x == 1:b1["bg"] = "white";x =0
b1.place(x=1,y=1) #placing the button
mainloop()
上面的代码有点复杂,所以如果你想要一个简单的方法,那么我已经制作了另一个代码。您还可以通过更改color1
和color2
(当前为白色和蓝色)的值来更改按钮的颜色:
from tkinter import * #for python2 Tkinter
root = Tk()
color1 = "white" #the default color
color2 = "blue" #the next color
def b1c(): #this function will run on button press
if b1.cget("bg") == color2:b1["bg"] =color1 #getting current button color
elif b1.cget("bg") == color1:b1["bg"] =color2
b1 = Button(root,text="Press me to change the color",bg=color1,command = b1c)
b1.place(x=1,y=1)
mainloop()
如果您在按下按钮时想要逐个更改颜色列表,那么您也可以执行此操作。在以下代码中,列表是colors
:
from tkinter import * #for python2 Tkinter
root = Tk()
colors = ["red","blue","green","sky blue"] #place your colors in it which you want to change 1-by-1 (from left to right)
def b1c():
for colo in colors:
if b1.cget("bg") == colo:
try:
color = colors[colors.index(colo)+1]
except:
color = colors[0]
b1["bg"] = color
break
b1 = Button(root,text="Press me to change the color",bg=colors[0],command = b1c)
b1.place(x=1,y=1)
mainloop()