如何在运行时更改按钮的颜色?

button1=Button(root,text="A1",width=8).grid(row=0,column=0)

button2=Button(root,text="A2",width=8).grid(row=0,column=1)


label1=Label(root,text="       ",padx=20).grid(row=0,column=2)


button22=Button(root,text="A3",width=8).grid(row=0,column=3,sticky='E')

button23=Button(root,text="A4",width=8).grid(row=0,column=4,sticky='E')

我正在尝试为学校项目制作座位安排系统。我有一个问题:单击按钮后如何更改按钮的颜色?单击该按钮后,我想更改已预订和可用座位的颜色。


皈依舞
浏览 138回答 1
1回答

ibeautiful

如果您只想更改单击时按钮的颜色,则需要使用.config()该按钮小部件上的方法。例如,如果一个按钮定义如下aButton = tk.Button(root, text='change my color').pack()然后要更改颜色(或几乎所有与该小部件相关的内容,如文本、命令或其他内容),请调用该方法aButton.configure(bg='#f0f', fg='#fff') # change to your required colors, bg is background, fg is foreground.也可以使用OR .config()(这2种方法的作用完全相同)aButton.config(bg='#f0f', fg='#fff')现在你如何知道按钮何时存在clicked或不存在。最简单直观的方法是定义它们functions并将bind它们连接(或)到按钮。现在你想如何做到这一点完全取决于用户的喜好。有些人喜欢为所有按钮创建单独的不同功能,有些人只喜欢创建一个。不过,对于您的情况,由于除了更改颜色之外您不需要做任何其他事情,因此单一功能就足够了。 重要在下面的示例代码中,我使用了lambda函数,一种特殊类型的函数,不需要单独定义。然而,这绝不是必要的为您提供工作示例from tkinter import *  # I don't recommend using global import. better use "import tkinter as tk"root = Tk()button1=Button(root,text="A1",width=8, command=lambda: button1.config(bg='#f00'))button1.grid(row=0,column=0)button2=Button(root,text="A2",width=8, command=lambda: button2.config(bg='#f00'))button2.grid(row=0,column=1)Label(root,text=" ",padx=20).grid(row=0,column=2)button22=Button(root,text="A3",width=8, command=lambda: button22.config(bg='#f00'))button22.grid(row=0,column=3,sticky='E')button23=Button(root,text="A4",width=8, command=lambda: button23.config(bg='#f00'))button23.grid(row=0,column=4,sticky='E')root.mainloop()使用函数from tkinter import *  # I don't recommend using global import. better use "import tkinter as tk"def changeColor(btn):    # Use your own highlight background argument here instead of bg    btn.configure(bg='#f00')root = Tk()button1=Button(root,text="A1",width=8, command=lambda: changeColor(button1))button1.grid(row=0,column=0)button2=Button(root,text="A2",width=8, command=lambda: changeColor(button2))button2.grid(row=0,column=1)Label(root,text=" ",padx=20).grid(row=0,column=2)button22=Button(root,text="A3",width=8, command=lambda: changeColor(button22))button22.grid(row=0,column=3,sticky='E')button23=Button(root,text="A4",width=8, command=lambda: changeColor(button23))button23.grid(row=0,column=4,sticky='E')root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python