我想在tkinter GUI中单击时更改按钮的背景色

时间:2019-05-04 06:24:05

标签: python tkinter

我有一个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()

单击打开按钮时,打开按钮的颜色需要从其默认颜色更改为绿色。如果单击关闭按钮,则关闭按钮的颜色需要更改为红色,而打开按钮的颜色将更改为其默认颜色。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

如果您不了解任何内容,我会对代码进行一些更改并添加了注释。对此应该有更好的解决方案(我在tkinter中不是很好),但我认为它足以进行测试...


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

window = Tk()


def open_command():
    print("Opening")
    # i destroy button here which was before and create new one
    global b1
    b1.destroy()
    b1 = Button(window, text="Open", font=("Times New Roman", 12), fg="green", bg="green", height=1, width=5,
                command=open_command)
    b1.grid(row=1)


def close_command():
    print("Closing")
    global b2
    b2.destroy()
    b2 = Button(window, text="Close", font=("Times New Roman", 12), fg="red", bg="green", height=1, width=5,
                command=close_command)
    b2.grid(row=2)


# first of all you need b1 and b2 (you had b and b (same buttons))
b1 = Button(window, text="Open", font=("Times New Roman", 12), fg="black", bg="white", height=1, width=5,
            command=open_command)
# i use grid instead of pack because it is placed exactly where you want
b1.grid(row=1)

b2 = Button(window, text="Close", font=("Times New Roman", 12), fg="black", bg="white", height=1, width=5,
            command=close_command)
b2.grid(row=2)

mainloop()