简体   繁体   中英

How to make button change colour in tkinter?

How do I make a button change colour in python tkinter 3?
I saw one using the self code but I don't like to use that. Here is the code:

from tkinter import *
from tkinter import ttk
root = Tk()

button = ttk.Button(root, text = "Click Me")
button.pack()
button.config(command = colour_change)

def colour_change():
    button.config(background= "green")

I am not entirely sure what you mean by "I saw one using the self code ..." but essentially, you can choose to set background colour of a button:

  1. At the time of creation by passing a parameter to constructor

    btn = Button(root, bg='red') # and other parameters if you like
  2. Whenever you want once the object is created until it's reference is valid by

    btn.config(bg='green')

    Now, when exactly you call this method is entirely up to you. It is just that the code snippet that you have shown is doing so at the click of that button itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM