Tkinter 按钮的突出显示对我不起作用

2024-03-21

根据已接受的答案这个帖子 https://stackoverflow.com/a/53648642/7475225指某东西的用途.configure(highlightbackground='red')按钮上应该在按钮周围应用颜色,但是在测试中我无法重现海报在其 gif 录制中演示的内容。

这是我的测试用例:(注意,即使复制粘贴海报代码,我也无法获得它们显示的突出显示效果)

import tkinter as tk


root = tk.Tk()

btn = tk.Button(root, text='test', bg="#000000", fg="#ffffff", highlightthickness=4, activebackground="#ffffff",
                activeforeground="#000000", highlightbackground='red', highlightcolor='red')
btn.pack()
btn.focus_set()
root.mainloop()

结果应用程序:

经过一些广泛的搜索,我没有找到太多highlightbackground以对同一问题进行问答的方式,所以可能缺少某些内容。我也尝试将焦点设置为本文档 https://www.tutorialspoint.com/python/tk_colors.htm表明小部件需要焦点,但结果相同。

也许它可能与版本或操作系统相关......

操作系统 - Windows 10 专业版

Python-3.6.2

使用 Krrr 的帖子更新了示例。所以现在这确实有点工作,但是这里的问题是它正在调整按钮的大小并且没有提供正确的突出显示颜色。

import tkinter as tk


def ResponsiveWidget(widget, *args, **kwargs):
    bindings = {
        '<FocusIn>': {'highlightbackground': 'red', 'highlightcolor':'red'},
        '<FocusOut>': {'highlightbackground': '#d9d9d9', 'highlightcolor':'SystemButtonFace'},
        '<Enter>': {'state': 'active'},
        '<Leave>': {'state': 'normal'}
    }
    for k, v in bindings.items():
        root.bind_class('Button', k, lambda e, kwarg=v: e.widget.config(**kwarg))


def update_active(event):
    global previous_button
    if previous_button != event.widget:
        previous_button.config(default='normal')
        event.widget.config(default='active')
        previous_button = event.widget


root = tk.Tk()
button_list = []
previous_button = None

for i in range(5):
    if i == 0:
        button_list.append(tk.Button(root, text='test', bg="#000000", fg="#ffffff", highlightthickness=5,
                                     activebackground="#ffffff", activeforeground="#000000", default='active'))
        previous_button = button_list[-1]
    else:
        button_list.append(tk.Button(root, text='test', bg="#000000", fg="#ffffff", highlightthickness=5,
                                     activebackground="#ffffff", activeforeground="#000000", default='normal'))
    button_list[-1].pack(padx=5, pady=5)
    button_list[-1].bind('<ButtonRelease-1>', update_active)

root.mainloop()

Results:

期待:


不幸的是,Windows 操作系统似乎没有触发state and default小部件配置正确。不过,这可以通过您自己的绑定来实现。

如果您只有少数需要此行为的小部件,您可以创建一个小部件包装器:

def ResponsiveWidget(widget, *args, **kwargs):
    bindings = {
        '<FocusIn>': {'default':'active'},    # for Keyboard focus
        '<FocusOut>': {'default': 'normal'},  
        '<Enter>': {'state': 'active'},       # for Mouse focus
        '<Leave>': {'state': 'normal'}
    }
    # Create the widget instance
    w = widget(*args, **kwargs)

    # Set the bindings for the widget instance
    for k, v in bindings.items():
        w.bind(k, lambda e, kwarg=v: e.widget.config(**kwarg))

    # Remember to return the created and binded widget
    return w

btn = ResponsiveWidget(tk.Button, root, text='test3', bg="#000000", fg="#ffffff", highlightthickness=10, activebackground="#ffffff",
                activeforeground="#000000", highlightbackground='red', highlightcolor='green')

btn2 = ResponsiveWidget(tk.Button, root, text='test4', bg="#000000", fg="#ffffff", highlightthickness=10, activebackground="#ffffff",
                activeforeground="#000000", highlightbackground='green', highlightcolor='red')

另一方面,如果您希望小部件的整个类始终正确触发默认/状态,您可以使用bind_class反而:

bindings = {
    '<FocusIn>': {'default':'active'},    # for Keyboard focus
    '<FocusOut>': {'default': 'normal'},  
    '<Enter>': {'state': 'active'},       # for Mouse focus
    '<Leave>': {'state': 'normal'}
}
for k, v in bindings.items():
    root.bind_class('Button', k, lambda e, kwarg=v: e.widget.config(**kwarg))

这似乎触发事件就好了。

如果您只想复制突出显示颜色的功能,则不太理想的方法是更改highlightcolor改为焦点配置:

bindings = {
        '<FocusIn>': {'highlightcolor':'red'},
        '<FocusOut>': {'highlightcolor': 'SystemButtonFace'},
        '<Enter>': {'state': 'active'},
        '<Leave>': {'state': 'normal'}
    }
for k, v in bindings.items():
    root.bind_class('Button', k, lambda e, kwarg=v: e.widget.config(**kwarg))

# Note this method requires you to set the default='active' for your buttons

btn = tk.Button(root, text='test', bg="#000000", fg="#ffffff", highlightthickness=10, activebackground="#ffffff",
                activeforeground="#000000", highlightcolor='SystemButtonFace', default='active')

# ...

我认为这更像是一种 hacky 方法。

编辑:为了完整起见,这里有一个 MCVE 使用bind_class:

import tkinter as tk

root = tk.Tk()
bindings = {
        '<FocusIn>': {'highlightcolor':'red'},
        '<FocusOut>': {'highlightcolor': 'SystemButtonFace'},
        '<Enter>': {'state': 'active'},
        '<Leave>': {'state': 'normal'}
    } 

for k, v in bindings.items():
    root.bind_class('Button', k, lambda e, kwarg=v: e.widget.config(**kwarg))

btns = list(range(5))
for btn in btns:
    btns[btn] = tk.Button(root, text='test', bg="#000000", fg="#ffffff", highlightthickness=5, activebackground="#ffffff",
        activeforeground="#000000", highlightcolor='SystemButtonFace', default='active', padx=5, pady=5)
    btns[btn].pack()

btns[0].focus_set()
root.mainloop()

和 MCVE 使用ResponsiveWidget功能:

import tkinter as tk

root = tk.Tk()
def ResponsiveWidget(widget, *args, **kwargs):
    bindings = {
        '<FocusIn>': {'highlightcolor':'red'},    # for Keyboard focus
        '<FocusOut>': {'highlightcolor': 'SystemButtonFace'},  
        '<Enter>': {'state': 'active'},       # for Mouse focus
        '<Leave>': {'state': 'normal'}
    }
    # Create the widget instance
    w = widget(*args, **kwargs)

    # Set the bindings for the widget instance
    for k, v in bindings.items():
        w.bind(k, lambda e, kwarg=v: e.widget.config(**kwarg))

    # Remember to return the created and binded widget
    return w

btns = list(range(5))
for btn in btns:
    btns[btn] = ResponsiveWidget(tk.Button, root, text=f'test{btn}', bg="#000000", fg="#ffffff", highlightthickness=10, activebackground="#ffffff",
        activeforeground="#000000", highlightcolor='SystemButtonFace', default='active', padx=5, pady=5)
    btns[btn].pack()

btns[0].focus_set()
root.mainloop()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Tkinter 按钮的突出显示对我不起作用 的相关文章

随机推荐

  • iCloud 和 NSFileWrapper:在“设置”中显示为 2 个不同的文件

    我有一个使用基于 NSFileWrapper 的 UIDocument 的应用程序 我的文件包装器是一个名为 XXX cp 的目录 其中有两个子文件 photo data 和 photo metadata 它似乎可以很好地保存和加载文档 但
  • Python 中的循环命名

    我最近读过这个问题 https stackoverflow com questions 886955 breaking out of nested loops in java 886979 886979其中有一个关于 Java 中标记循环的
  • 丢失 .idea 文件夹后如何在 Android Studio 中重新创建项目?

    我一直试图通过尝试一些东西来了解 Android Studio IDE 的工作原理 我从 Google 存储库导入了示例项目之一 Android DataLayer 它附带了一些配置的模块 然后我删除了 idea文件夹并想再次打开该项目 但
  • 我们可以使用 data.table 按组设置顺序吗?

    简单的问题 我想用data table setorder在我的 DT 上 但我不能按组执行此操作 是否可以 在此示例中 我订购了整个 DT DT data table a rep c C A D B E each 4 b sample 1
  • 在自定义格式化程序中访问 rowObejct

    在 jqgrid wikki 中 我读到 虽然使用 xml 数据类型 rowobject 将不是一个数组 在 json 中 我使用 rowobject 1 2 等获取了列值 但是如何使用 xml 数据类型来实现这一点 请提供使用 xml 数
  • 确定在哪个表视图中按下了单元格按钮?

    我有像测验这样的表格视图单元格 在每个单元格中我都有一个按钮 我如何识别按下了哪个单元格按钮 也许通过 IndexPath 这就是我将按钮连接到的方式 func tableView tableView UITableView cellFor
  • 带有 SDK 4.2 的 Xcode 始终启动 iPad 模拟器

    为什么 Xcode 在更新到 SDK 4 2 后总是在 iPad Simulator 而不是 iPhone 中运行我的应用程序 如果我选择 iPhone Simulator 作为活动可执行文件 它不会存储我的首选项 并在任何新的 构建和运行
  • 应用程序关闭后无法保持 Android 服务处于活动状态

    我正在尝试生成一个始终保持活动状态的服务 即使用户关闭应用程序也是如此 根据这些线程 当应用程序关闭时保持位置服务处于活动状态 https stackoverflow com questions 21441232 keep location
  • 如何判断在touchesBegan中哪个对象被触摸了?

    我知道这是一个非常常见的问题 但每个网站上的所有答案都不起作用 如果你还是不明白我的意思 那么也许这行代码会帮助你理解 void touchesBegan NSSet touches withEvent UIEvent event UITo
  • 有没有办法将 Google Sheets 工作簿中的值绘制到 TradingView pinescript 中?

    我正在尝试将 GoogleSheets 工作簿中计算的值绘制在交易视图图表上 我无法在 Tradingview 中进行相同的计算 因为这些值来自动态网页 所以我在 excel 中进行计算 并且想知道是否可以以某种方式将这些值发送到 Trad
  • PySpark 时间戳的毫秒数

    我试图获取两个时间戳列之间的差异 但毫秒消失了 如何纠正这个问题 from pyspark sql functions import unix timestamp timeFmt yyyy MM dd HH mm ss SSS data 1
  • 在 C# 中实现套接字侦听器的最佳方法

    我已经搜索过答案 但找不到类似的东西 我对 C 相当陌生 我需要使用 WinForms 在 C 中创建一个程序 它基本上有 2 个组件 UI 然后我需要一个永久侦听套接字 TCP 端口的进程 如果收到任何内容 那么我需要引发一个事件或类似的
  • 计算一年中第一周的星期一的最简单方法是什么

    我想过去一年并得到一个代表第一周第一个星期一的日期 so 如果一个传入2011 我会回来的2011 年 1 月 3 日 如果一个传入2010 我会回来的2010 年 1 月 4 日 private DateTime GetFirstMond
  • Images.xcassets 违反目标法则

    好吧 所以我正在为这个问题拔牙 我真诚地希望我犯了一个愚蠢的错误 涉及到一些深夜 简短的背景故事 我们正在构建一个需要品牌化的产品 因为多个客户将共享 90 相同的 UI 和代码 并使用一些配置选项来打开 关闭以及不同的颜色 字体和图像等
  • 当我第二次运行测试时,为什么在 Mongoose 中出现错误“无法覆盖编译后的模型”?

    我读过相关帖子 编译 Mongoose 后无法覆盖模型 https stackoverflow com questions 19051041 cannot overwrite model once compiled mongoose 问题是
  • 改变排序对象行为

    使用映射到 Linux 共享的驱动器时 文件名区分大小写 PowerShell 按预期处理此问题 但我想以类似于 C 语言环境中使用的排序顺序的方式对输出进行排序 这意味着按字符值从 U 0000 一直到 U 升序排序10FFFF 例如 0
  • HTML 标签的正则表达式 [重复]

    这个问题在这里已经有答案了 我有一个 HTML 页面 tr 类 我需要捕获这些标签之间的文本 我尝试过Regex i tr
  • Javascript:拖放图像标签

    我想知道如何使用 javascript 拖放图像标签 我知道 html5 每个元素都可以拖动 但我想让它在旧浏览器上工作 我已经使用javascript进行了拖放操作 除了在ie和firefox中 当鼠标按下时 它工作得很好 除非用户单击它
  • Flutter:为什么这个流构建器不起作用?

    所以 我刚刚开始从事一个 flutter 项目 对整个体验还很陌生 我刚刚通过创建几个更新 删除和添加文档的按钮 成功地将 firebase firestore 集成到我的项目中 但是 我还想添加一个 Streambuilder 以及在同一
  • Tkinter 按钮的突出显示对我不起作用

    根据已接受的答案这个帖子 https stackoverflow com a 53648642 7475225指某东西的用途 configure highlightbackground red 按钮上应该在按钮周围应用颜色 但是在测试中我无