【问题标题】:How do I change background colour of a button on hover in Tkinter?如何在 Tkinter 中更改悬停按钮的背景颜色?
【发布时间】:2021-03-22 02:01:13
【问题描述】:

我想在 Python Tkinter 模块中更改鼠标光标悬停时按钮的背景和前景色。在将按钮打包到主窗口之前,我可以更改一次按钮的背景颜色。 但是在window.mainloop() 行之后,我不能再执行行,直到主窗口被破坏(或关闭)。

我在问即使在window.mainloop() 行之后,有什么方法可以更改鼠标悬停时的按钮颜色(背景和前景)?

我的代码

import tkinter

window = tkinter.Tk()
button = tkinter.Button(window, text="Test", fg='#03045e', command=terminate_instant,
                        relief=tkinter.RIDGE, bg='#caf0f8', activebackground='#ef233c',
                        activeforeground='white')
button.pack(side=tkinter.BOTTOM)
window.mainloop()

【问题讨论】:

  • 我不明白你到底想要什么,因为按钮的颜色在鼠标悬停时已经改变(activeforeground 和 activebackground)。
  • @j_4321:不,这不正确,它不正确。
  • @martineau 它在我的电脑上运行 (Linux)
  • @j_4321:它不在我的 Windows 机器上。另外,我想昨天我在这里读到了一些内容,表明在 MacOS 上,您无法更改 Buttons 的背景颜色——因此似乎存在与此相关的特定于操作系统的行为。找到我读到的:How to change the foreground or background colour of a Tkinter Button on Mac OS X?
  • @martineau 是的,可能有几种依赖于操作系统的样式行为。当我将光标放在按钮上时,它会根据bgactivebackground 选项的设置从浅蓝色变为深红色。另一方面,acw1668 的回答对我不起作用,因为在输入按钮时设置的bgactivebackground 选项覆盖

标签: python tkinter button tkinter-button


【解决方案1】:

您可以使用<Enter><Leave> 事件来更改按钮的fgbg 颜色:

import tkinter

window = tkinter.Tk()
button = tkinter.Button(window, text="Test", fg='#03045e', command=terminate_instant,
                        relief=tkinter.RIDGE, bg='#caf0f8', activebackground='#ef233c',
                        activeforeground='white')
button.pack(side=tkinter.BOTTOM)
button.bind("<Enter>", lambda e: button.config(fg='#caf0f8', bg='#03045e'))
button.bind("<Leave>", lambda e: button.config(fg='#03045e', bg='#caf0f8'))
window.mainloop()

【讨论】:

  • 请注意,此解决方案是特定于操作系统的:在 Linux 上,activebackgroundactiveforeground 按预期工作并覆盖绑定中设置的 bgfg
  • 正如@j_4321 所说,这是否有效取决于操作系统(在 Windows 上按预期工作)。所以……这将是 IMO 最大的可移植性。
  • @acw1668 我认为 Enter 绑定中的 bg 有错字:应该是 '#ef233c',而不是 '#03045e'(可能是复制/粘贴错误)
  • @j_4321 颜色来自创建按钮时的fgbg 选项。
  • @acw1668 好的,我只是认为 OP 想在将鼠标悬停在按钮上时使用来自 activebackground 和 activeforeground 选项的颜色。无论如何,既然您提供了代码,任何人都可以根据自己的喜好轻松更改颜色。
猜你喜欢
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 2013-06-26
  • 2022-12-03
  • 1970-01-01
  • 2022-12-04
相关资源
最近更新 更多