【问题标题】:Alternate Between Two Colors For Text [closed]在文本的两种颜色之间交替[关闭]
【发布时间】:2024-05-04 14:30:04
【问题描述】:

有没有办法在每次单击时切换按钮的颜色(例如,它从白色开始,第一次单击时变为蓝色,下次单击时变为白色,如果单击它第三次它再次变成蓝色......并且以相同的模式继续)。

如果可能的话,python 有没有办法记住上一个会话的按钮颜色,并在下次启动时保持该颜色?

【问题讨论】:

  • 请发布您的代码。

标签: python button tkinter colors


【解决方案1】:

是的,这是可能的。

这里,当按下按钮时,文本颜色会从红色切换为蓝色。

如果您将按钮选项的关键字参数从 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()

【讨论】:

    【解决方案2】:

    与其他答案不同,我建议采用面向对象的方法。 下面的示例使用 tkinter Button 类作为基础,但添加了 on_coloroff_color 参数来指定您希望按钮在打开/关闭时的颜色。

    通过这种方式,您可以拥有任意数量的具有相似行为的按钮,但不必具有更改每个按钮状态的功能。这种行为是在类中定义的。

    on_coloroff_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)
    

    这将在窗口关闭时调用apponClose 方法。在此方法中,您只需收集按钮的各种状态并将它们写入文件。例如

    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']
    

    【讨论】:

      【解决方案3】:

      您可以在按下按钮时更改按钮的颜色。有几种方法可以做到这一点。我已经发布了一些sn-ps。

      这是一个代码:

      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()
      

      上面的代码有点复杂,所以如果你想要一个简单的方法,那么我已经编写了另一个代码。您还可以通过更改color1color2 的值来更改按钮的颜色(当前为白色和蓝色)

      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()
      

      【讨论】:

        最近更新 更多