How do I change the colour of my button and label on Tkinter?

后端 未结 4 488
盖世英雄少女心
盖世英雄少女心 2021-01-26 12:35

My task is to create a label and button on Tkinter. The button has to change the label, and I have to change the colour of the button and the label. I have changed the colour of

4条回答
  •  时光取名叫无心
    2021-01-26 13:25

    So configuring a buttons colors is a bit different when using tkinter button VS a ttk style button.

    For a tkinter button you would use the background = "color" argument like the following:

    button1 = Button( rootWindow, text="Change Label",
                          background = 'black', foreground = "white", command=change)
    

    For a ttk button you would configure the style and then use the style = "style name" argument like the following.

    style = ttk.Style()
    style.configure("BW.TLabel", foreground="white", background="black")
    
    buttonTTK = ttk.Button( rootWindow, text="TTK BUTTON",style = "BW.TLabel", command=change)
    

    More information on ttk configs can be found here

    from tkinter import *
    from tkinter import ttk
    
    def change():
        print("change functon called")
    
    def main():
        rootWindow = Tk()
    
        label = ttk.Label( rootWindow, text="Hello World!",
                           background = 'black', foreground = "white")
        label.pack()
    
        button1 = Button( rootWindow, text="Change Label",
                              background = 'black', foreground = "white", command=change)
        button1.pack()
    
        style = ttk.Style()
        style.configure("BW.TLabel", foreground="white", background="black")
    
        buttonTTK = ttk.Button( rootWindow, text="TTK BUTTON",style = "BW.TLabel", command=change)
        buttonTTK.pack()
    
        rootWindow.mainloop()
    
    main()
    

    Result:

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题