首页 > 解决方案 > [Tkinter]将键盘键绑定到单选按钮

问题描述

我正在尝试将F1密钥绑定到我的 tkinter GUI 中的单选按钮。我试过这个

import tkinter as tk

def stack():
   print('StackOverflow')

root = tk.Tk()

v = tk.IntVar()

RadBut = tk.Radiobutton(root, text = 'Check', variable = v, value = 1, command = stack)
RadBut.pack() 

RadBut.bind_all("<F1>", stack)

root.mainloop()

如果我运行它并尝试按 f1 它给出

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\MyName\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
TypeError: stack() takes 0 positional arguments but 1 was given

但是用鼠标点击按钮可以正常工作。

提前致谢

标签: pythonbuttontkinterbind

解决方案


就像@acw1668 所说,你需要给stack()函数一个参数。

我想补充一点,它不一定是None.

这是您的代码:

from tkinter import *

def stack(event = "<F1>"):
   print('StackOverflow')

root = Tk()

v = IntVar()

RadBut = Radiobutton(root, text = 'Check', variable = v, value = 1, command = stack)
RadBut.pack() 

RadBut.bind_all("<F1>", stack)

root.mainloop()

希望这可以帮助!


推荐阅读