小部件中的 tkinter 默认按钮



这似乎很容易...

我写了一个对话框小部件,其中我放置了一些条目、按钮等 - 其中有一个按钮我想通过鼠标单击激活,但也按回车键激活。我前段时间读到只需要设置其默认选项,但我认为它在最新版本中发生了变化。

你知道怎么设置它吗?

谢谢!

'<Return>' 事件的回调绑定到窗口(在 Tkinter 中通常称为 root(或包含帧。 让回调接受事件参数(可以忽略(,并将其invoke()按钮的回调中。

root.bind('<Return>', (lambda e, b=b: b.invoke())) # b is your button
def myaction():
    print('Your action in action')
def myquit():
    root.destroy()
root = Tk()
label = Label(root, text='Label Text').pack(expand=YES, fill=BOTH)
label.bind('<Return>', myaction)
label.bind('<Key-Escape>', myquit)
ok = Button(label, text='My Action', command=myaction).pack(side=LEFT)
quit_but = Button(label, text='QUIT', command=myquit).pack(side=RIGHT)
root.mainloop()
  1. 必须先声明函数。
  2. 请注意,"我的操作"按钮和 Return 键都调用 myaction 和"退出",而 Esc 键都调用myquit

希望有帮助。

最新更新