【问题标题】:How to pass more arguments through tkinter bind如何通过 tkinter 绑定传递更多参数
【发布时间】:2019-11-03 11:13:12
【问题描述】:

如何通过 tkinter 的 bind 方法传递更多参数?
例如:

tk = Tk()
def moveShip(event,key):
    if event.keysym == 'Down' and player1.selectedCoord[1] != 9:
        if key == 'place':
            player1.selectedCoord[1] += 1
    elif event.keysym == 'Up' and player1.selectedCoord[1] != 0:
        if key == 'place':
            player1.selectedCoord[1] -= 1
    elif event.keysym == 'Left' and player1.selectedCoord[0] != 0:
        if key == 'place':
            player1.selectedCoord[0] -= 1
    elif event.keysym == 'Right' and player1.selectedCoord[0] != 9:
        if key == 'place':
            player1.selectedCoord[0] += 1

tk.bind("<Key>", command=moveShip(event,'place'))

而不是

tk.bind("<Key>", moveship)

当我运行第一个时,它说事件未定义

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您始终可以将回调函数包装在 lambda 中。

    tk.bind('<Key>', lambda event: moveShip(event, 'place'))
    

    另一个选项是使用 functool 中的 partial 创建一个函数,该函数已设置默认值 key

    from functools import partial
    
    moveShip_place = partial(moveShip, key='place')
    
    tk.bind('<Key>', moveShip_place)
    

    【讨论】:

    • 没问题。如果这可以解决您的问题,请不要忘记将问题标记为已回答(复选标记)。
    猜你喜欢
    • 2017-11-26
    • 2016-03-03
    • 2011-05-24
    • 2015-12-05
    • 2019-09-19
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多