簡體   English   中英

我想在 tkinter GUI 中單擊時更改按鈕的背景顏色

[英]I want to change the background color of the button when I click in tkinter GUI

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

單擊打開按鈕時,打開按鈕的顏色需要從其默認顏色更改為綠色。 如果我們點擊關閉按鈕關閉按鈕顏色需要更改為紅色,打開按鈕顏色更改為其默認顏色。

您可以簡單地使用.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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM