如何通过 tkinter 绑定传递更多参数 [英] How to pass more arguments through tkinter bind

查看:36
本文介绍了如何通过 tkinter 绑定传递更多参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I pass more arguments through tkinter's bind method?
for the example:

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)

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

when I run the first one, it says the event is not defined

推荐答案

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

You can always wrap the callback function in a lambda.

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

另一种选择是使用 functool 中的 partial 来创建一个函数,其中 key 的默认值已经设置.

The other option is to use partial from functool to create a function with the default value of key already set.

from functools import partial

moveShip_place = partial(moveShip, key='place')

tk.bind('<Key>', moveShip_place)

这篇关于如何通过 tkinter 绑定传递更多参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆