感应按钮按下python

时间:2014-07-08 13:36:23

标签: python tkinter

所以我为一个我们正在做的小项目编写了这段代码

#!/usr/bin/python
import Tkinter
import tkMessageBox

win = Tkinter.Tk()

def add_num(number):
    number=number+5

win.geometry("500x300")
win.wm_title("Numbers")
butt=Tkinter.Button(win, text ="HOLD MEH!!!", command = add_num(5))
butt.pack()

win.mainloop()

现在这个程序只在我点击它时会广告数字。这里的最简单的方式是什么,所以如果按下它会反复调用该函数?我真的希望它能够简单

2 个答案:

答案 0 :(得分:0)

您可能想尝试下面的演示。按住按钮时,MyButton类会尽快重复command。如果需要,您可以更改start方法以更少地安排command。只需调用after方法,并记住在适当的等待时间内填写ms参数。

#! /usr/bin/env python3
from tkinter import *

class Demo(Frame):

    QVGA = 320, 240

    @classmethod
    def main(cls):
        NoDefaultRoot()
        root = Tk()
        root.title('Demo')
        root.minsize(*cls.QVGA)
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        frame = cls(root)
        frame.grid(sticky=NSEW)
        root.mainloop()

    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master, cnf, **kw)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.var = IntVar(self)
        self.label = Label(self, textvariable=self.var)
        self.label.grid(sticky=NSEW)
        self.button = MyButton(self, text='Hold Me', command=self.add)
        self.button.grid(sticky=EW)

    def add(self):
        self.var.set(self.var.get() + 1)

class MyButton(Button):

    def __init__(self, master=None, cnf={}, **kw):
        self.command = kw.pop('command')
        super().__init__(master, cnf, **kw)
        self.bind('<ButtonPress-1>', self.start)
        self.bind('<ButtonRelease-1>', self.stop)

    def start(self, event):
        self.handle = self.after_idle(self.start, event)
        self.command()

    def stop(self, event):
        self.after_cancel(self.handle)

if __name__ == '__main__':
    Demo.main()

答案 1 :(得分:0)

command=期望函数名称没有()(和参数)

使用

command = add_num(5)

您运行add_num(5)并将此功能的结果分配给command=

您的功能没有return,因此默认返回None

Finnaly你的代码几乎意味着:

add_num(5) # run function once
Button( commnad=None ) # no function assigned to `command=`

您可以通过两种方式使用参数来协助函数:

1 - 使用其他功能:

def add_five():
   add_num(5)

Button( commnad=add_five )

2 - lambda

Button( commnad= lambda : add_num(5) )
Button( commnad=lambda:add_num(5) ) # less spaces in code

BTW:您应该将结果保存在不同的变量中以便一次又一次地添加

result = 0

def add_num(number):
    global result 

    result = result + number

    print "new result:", result