如何在python中回调方法?

时间:2015-05-12 09:29:56

标签: python tkinter gpio

我正在制作一个项目,每当我停止秒表时,它会将时间更新为列表框。它可以在self.m listbox中更新。但是无法将其更新为topscoreslistbox

printFunctionStop函数中,我在类中回调Stop方法。但是我不知道如何在主函数中调用TopscoresStop

Stop方法和TopscoresStop方法执行相同的操作。然而,不同的是一个在课堂上,一个在主要功能中。

那么我如何在TopscoresStop中的主函数中调用方法printFunctionStop

class StopWatch(Frame):  
    def Stop(self):                                    
        """ Stop the stopwatch, ignore if stopped. """
        tempo = self._elapsedtime - self.lapmod2
        if self._running:
            self.after_cancel(self._timer)            
            self._elapsedtime = time.time() - self._start    
            self._setTime(self._elapsedtime)
            self._running = 0

        if len(self.laps) == 3:
            return

        self.laps.append(self._setLapTime(tempo))
        self.m.insert(END, (str(self.one.get()) , "%.2f" % self._elapsedtime))
        self.m.yview_moveto(1)

def main():
    def Topscores():
        toplevel() = Toplevel()
        toplevel.title("Top Scores")
        topscoreslistbox = Listbox(toplevel, selectmode=EXTENDED, height=3, width=20, font=("Helvetica", 26))                   
        topscoreslistbox.pack(side=RIGHT, fill=BOTH, expand=1, pady=5, padx=2)

        first = Label(toplevel, text=("1st"), font=("Algerian", 30))
        first.pack(side=TOP)

        second = Label(toplevel, text=("2nd"), font=("Algerian", 30))
        second.pack(side=TOP)     

        third = Label(toplevel, text=("3rd"), font=("Algerian", 30))
        third.pack(side=TOP)          

    def TopscoresStop():
        tempo = sw._elapsedtime - sw.lapmod2
        if sw._running:
            sw.after_cancel(sw._timer)            
            sw._elapsedtime = time.time() - sw._start    
            sw._setTime(sw._elapsedtime)
            sw._running = 0

        if len(sw.laps) == 3:
            return

        sw.laps.append(sw._setLapTime(tempo))
        topscoreslistbox.insert(END, (str(sw.one.get()) , "%.2f" % sw._elapsedtime))
        topscoreslistbox.yview_moveto(1)

    def printFunctionStop(channel):

        sw.event_generate("<<Stop>>", when = "tail")    

    GPIO.add_event_detect(16, GPIO.FALLING, callback = printFunctionStop, bouncetime=300)
    sw.bind("<<Stop>>", lambda event:sw.Stop()) 

1 个答案:

答案 0 :(得分:1)

您是否尝试将该函数作为参数传递给printfunctionstop

抱歉,还不能发表评论。

E.g。

def a():
    print('hi')

def b(func):
    func()

def main():
    b(a)

main()

主要应打印'hi'