Search code examples
pythonbuttontkinterbind

[Tkinter]Binding Keyboard Keys to a Radiobutton


I am trying to bind F1key to my radiobutton in my tkinter GUI. I tried this

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()

If I run this and try to press f1 it gives out

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

But clicking on the button with mouse works fine.

Thanks in Advance


Solution

  • Like @acw1668 said, you need to give an argument to the stack() function.

    I would like to add that it doesn't have to be a None.

    Here is your code:

    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()
    

    Hope this helps!