将功能绑定到键不起作用

Binding a function to a key is not working

我的代码:

import tkinter

master = tkinter.Tk()
master.title("test1")
master.geometry("300x300")

masterFrame = tkinter.Frame(master)

masterFrame.pack(fill=tkinter.X)

checkboxArea = tkinter.Frame(masterFrame, height=26)

checkboxArea.pack(fill=tkinter.X)

inputStuff = tkinter.Frame(masterFrame)

checkboxList = []

def drawCheckbox():
    checkboxList.append(entry.get())
    entry.delete(0,tkinter.END)
    checkboxRow = tkinter.Frame(checkboxArea)
    checkboxRow.pack(fill=tkinter.X)
    checkbox1 = tkinter.Checkbutton(checkboxRow, text = checkboxList[-1])
    checkbox1.pack(side=tkinter.LEFT)
    deleteItem = tkinter.Button(checkboxRow, text = "x", command=checkboxRow.destroy, bg="red", fg="white", activebackground="white", activeforeground="red")
    deleteItem.pack(side=tkinter.RIGHT)

def bindToEnter():
    master.bind('<Return>', drawCheckbox)

def createInputStuff():
    paddingFrame = tkinter.Frame(inputStuff, height=5)
    paddingFrame.pack(fill=tkinter.X)
    buttonDone.pack()
    inputStuff.pack()
    buttonAdd.pack_forget()
    bindToEnter()

def removeInputStuff():
    inputStuff.pack_forget()
    buttonAdd.pack()
    buttonDone.remove()

buttonDone = tkinter.Button(inputStuff, text = "Close Input", command=removeInputStuff)


buttonAdd = tkinter.Button(masterFrame, text="Add Item", command=createInputStuff)
buttonAdd.pack()


topInput = tkinter.Frame(inputStuff)
bottomInput = tkinter.Frame(inputStuff)

topInput.pack()
bottomInput.pack()

prompt = tkinter.Label(topInput, text="What do you want your checkbox to be for?")
prompt.pack()
entry = tkinter.Entry(bottomInput, bd=3)
entry.pack(side=tkinter.LEFT)
buttonConfirm = tkinter.Button(bottomInput, text="Confirm", command=drawCheckbox)
buttonConfirm.pack(side=tkinter.LEFT)

master.mainloop()

这个想法是让按下 Return/Enter 和按下 "Confirm" 按钮做同样的事情,运行ning drawCheckbox。这项工作仍在进行中,当 removeInputStuff 为 运行 时,我将解除 drawCheckbox 函数与 Enter 键的绑定。尽管如此,我仍然不明白为什么按 Enter 键没有 运行 它绑定到的功能。

当您将一个函数 fct 绑定到一个键(或任何其他类型的事件)时,该函数将使用一个参数调用,例如 fct(event)event 具有各种属性取决于事件的种类(鼠标位置,...)。你的问题是你调用的函数 drawCheckbox 不接受任何参数,所以每次你按 Enter 时,它都会引发错误

TypeError: drawCheckbox() takes 0 positional arguments but 1 was given

要更正它,您可以使用默认参数定义您的函数,

def drawCheckbox(event=None):
    ...

或者您可以使用 lambda 函数进行绑定

master.bind('<Return>', lambda event: drawCheckbox())