tkinter中的command和bind有什么区别? [英] What is the difference between command and bind in tkinter?

查看:287
本文介绍了tkinter中的command和bind有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使一个按钮在按下时打印字符串,并在释放按钮时打印另一个字符串.我知道 command 属性和 bind 方法,但是我想知道是否有可能仅使用属性来完成它,或者是否必须使用方法.使用这段代码:

I'm trying to make a button print a string when it's pressed and print another when it's released. I know about the command atribute and the bind method, but I would like to know if it's possible to accomplish it only using atributes or if I have to use methods. With this piece of code:

class motor:
     def __init__(eleMesmo, eixo , valorZero):
         eleMesmo.eixo = eixo
         eleMesmo.zero = valorZero

     def aumenta(self):
         print(self.eixo + str(self.zero+5))
     def diminui(self):
         print(self.eixo + str(self.zero-5))
     def para(self):
    print(self.eixo + str(self.zero))

eixox = motor('x',90)
eixoy = motor('y',90)


class Interface:
    def __init__(elemesmo, widget):
         quadro = Frame(widget)
         quadro.pack()
         elemesmo.aumentarY = Button(quadro,text="Aumentar Y",height=10,width=20,command=eixoy.aumenta)
         elemesmo.aumentarY.pack(side=TOP)
         elemesmo.diminuirY = Button(quadro,text="Diminuir Y",height=10,width=20,command=eixoy.diminui)

当按下按钮 aumentarY 时,我可以为对象 eixo y 调用方法 aumenta .我想在释放按钮 aumentarY 时为对象 eixo y 调用方法 para .我该怎么办?

I can call the method aumenta for object eixo y when button aumentarY is pressed. I would like to call the method para for object eixo y when button aumentarY is released. How I can do it?

推荐答案

所有概述了事件类型在这里,您正在寻找< Button-1> (单击按钮1(如果您是右手,则单击鼠标左键))和< ButtonRelease-1>.(释放鼠标按钮1(如果您是右手,则释放鼠标左键)).

All Event types are outlined here, you are looking for <Button-1> (click down on button 1 (left mouse button if you are right handed)) and <ButtonRelease-1> (release mouse button 1 (left button if you are right handed)).

请注意,如果您将两者都绑定,则不会使用 command .

Note I wouldn't use command if you bind both of these.

 elemesmo.aumentarY = Button(quadro,text="Aumentar Y",height=10,width=20)
 elemesmo.aumentarY.bind("<Button-1>",eixoy.aumenta)
 elemesmo.aumentarY.bind("<ButtonRelease-1>",eixoy.para)

但是,您必须知道,使用 bind 时,回调是通过

However you must know that when using bind the callback is called with an Event object, if you don't need it you can just add an optional and unused parameter to the callback:

 def aumenta(self, event=None):
     print(self.eixo + str(self.zero+5))
 def diminui(self, event=None):
     print(self.eixo + str(self.zero-5))
 def para(self, event=None):
    print(self.eixo + str(self.zero))

这篇关于tkinter中的command和bind有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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