【问题标题】:How do I bind a command to the enter key in Tkinter? [duplicate]如何将命令绑定到 Tkinter 中的 enter 键? [复制]
【发布时间】:2020-05-31 15:56:00
【问题描述】:

我见过像 bind 命令这样的解决方案,但是当我给它参数('',self.checkguess)时,它会出错,说需要一个参数。

self.input = Entry(self.win)
self.input.place(x = 0, y = 80)
self.input.focus_set()
self.attempt = Button(self.win, text = "Guess", width = 6, height = 2, command = self.check_guess)
self.attempt.place(x = 0, y = 120)
self.win.bind('<Return>', self.check_guess)

win 是窗口的名称

这是错误信息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: check_guess() takes 1 positional argument but 2 were given

这里是 check_guess 的代码:

def check_guess(self):
        print("hello")
        global guesses
        global correctguesses
        global word2

【问题讨论】:

  • 好的,我想我可能做错了什么。另外,为了澄清,check_guess 与添加的代码属于同一类
  • 回调方法应该接受另一个参数,即事件对象
  • def check_guess(self, event):...

标签: python tkinter


【解决方案1】:

将键绑定到函数激活时,您正在添加多个参数。

当你定义'check_guess'时

而不是def check_guess(self):

试试:

def check_guess(*args):

*args 几乎允许多个参数通过一个函数传递

【讨论】:

    猜你喜欢
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多