【问题标题】:I want to change the background color of the button when I click in tkinter GUI当我在 tkinter GUI 中单击时,我想更改按钮的背景颜色
【发布时间】:2019-09-22 14:33:31
【问题描述】:

我有一个 python GUI 代码可以打开和关闭。我需要修改代码,比如当我按下打开按钮时,按钮颜色变为绿色,当我按下关闭按钮时,打开按钮颜色变为默认颜色。

from serial import*
from time import*
from tkinter import*

window = Tk()

def open_command():
    print("Opening")

def close_command():
    print("Closing")

b = Button(window, text = "Open", font = ("Times New Roman", 12), fg = "green", bg = "white", height = 1, width = 5, command = open_command).pack()
b = Button(window, text = "Close", font = ("Times New Roman", 12), fg = "red", bg = "white", height = 1, width = 5, command = close_command).pack()

mainloop()

单击打开按钮时,打开按钮的颜色需要从默认颜色更改为绿色。如果我们点击关闭按钮,关闭按钮颜色需要变为红色,打开按钮颜色变为默认颜色。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您可以简单地使用.config(bg=...) 将按钮的背景颜色更改为您想要的任何颜色,如下所示:

    import tkinter as tk
    
    window = tk.Tk()
    
    def open_command():
        open_btn.config(bg='green')
        close_btn.config(bg='white')
    
    def close_command():
        open_btn.config(bg='white')
        close_btn.config(bg='red')
    
    font=('Times New Roman', 12)
    open_btn = tk.Button(window, text='Open', font=font, fg='green', bg='white', width=5, command=open_command)
    open_btn.pack()
    close_btn = tk.Button(window, text='Close', font=font, fg='red', bg='white', width=5, command=close_command)
    close_btn.pack()
    
    window.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2017-08-02
      • 2014-10-10
      • 2019-04-14
      • 1970-01-01
      • 2015-11-06
      相关资源
      最近更新 更多