【问题标题】:[Tkinter]Binding Keyboard Keys to a Radiobutton [closed][Tkinter]Binding Keyboard Keys to a Radiobutton [closed]
【发布时间】:2020-05-19 03:26:44
【问题描述】:

我正在尝试将F1key 绑定到我的 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

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

提前致谢

【问题讨论】:

  • bind 的回调函数将接收事件对象作为参数。所以给stack()添加一个参数:def stack(event=None),那么bind和command都可以使用。

标签: python button tkinter bind


【解决方案1】:

就像@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()

希望这会有所帮助!

【讨论】:

  • 嘿@BluNyte,你介意支持我的回答吗?我真的很感激。谢谢!
  • 当然,谢谢你的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 2014-07-28
  • 2020-06-24
  • 1970-01-01
  • 2022-12-26
  • 1970-01-01
相关资源
最近更新 更多