【问题标题】:Problems with tkinter button bindings and behaviourtkinter 按钮绑定和行为的问题
【发布时间】:2020-08-18 15:40:33
【问题描述】:

我正在尝试找出如何使 enter 键的行为与 tkinter 中的空格键相同。 到目前为止,唯一出现的是将回车键绑定到一个按钮。它的功能,到目前为止一切都很好。

但是:在视觉上它们并不相同。当您按下空格键时,按钮的浮雕会瞬间变为 SUNKEN。键绑定或调用 invoke() 没有相同的视觉效果。

在尝试寻找答案时,我可能发现了一个错误。当使用空格键按下按钮 5-10 秒时,RELIEF 将永久更改为 SUNKEN。不管你等多久。所以,这是我需要解决方法的另一件事。也许在函数调用重置按钮的状态之后......我会试试的。

以下是无法按预期工作的示例代码:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")
# if you press the enter key, buttons will call their own invoke function
# yet they won't show the effect of pressing space or clicking a button.
# When you press space or click a button the RELIEF will get changed.
# HOWEVER: When you hold space, the relief will get changed to SUNKEN permanently.
# That might me a bug.
root.bind_class("Button", "<Key-Return>", lambda event: event.widget.invoke())

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

# it's not a callback issue that the button remains SUNKEN after holding space for a bit.
button2 = tk.Button(root, text="this button has no command")    
button2.pack()

root.mainloop()

编辑:我在 win10 上。

【问题讨论】:

  • 我无法在 OSX 上重现
  • 尝试将event.widget.invoke() 更改为event.widget.event_generate('&lt;space&gt;')
  • 这就像一个魅力!和一个绝妙的解决方案。这基本上是:当你按回车时,你按空格。

标签: python button tkinter binding widget


【解决方案1】:

@acw1668 发布的解决方案就像一个魅力。

现在的代码是:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")
# When you hold space, the relief will get changed to SUNKEN permanently.
# That might me a bug.
root.bind_class("Button", "<Key-Return>", lambda event: event.widget.event_generate("<space>"))

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

# it's not a callback issue that the button remains SUNKEN after holding space for a bit.
button2 = tk.Button(root, text="this button has no command")    
button2.pack()

root.mainloop()

但它并没有解决沉没的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2015-03-02
    • 2011-10-17
    • 2018-08-28
    • 2013-08-15
    • 2020-11-18
    相关资源
    最近更新 更多