【问题标题】:How to call back methods in python?如何在python中回调方法?
【发布时间】:2015-05-12 09:29:56
【问题描述】:

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

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

Stop 方法和TopscoresStop 方法做同样的事情。但是不同的是,一个在类中,一个在主函数中。

那么我如何在printFunctionStop的主函数中调用方法TopscoresStop有人知道吗?

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()) 

【问题讨论】:

    标签: python tkinter gpio


    【解决方案1】:

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

    抱歉,还不能制作 cmets。

    例如

    def a():
        print('hi')
    
    def b(func):
        func()
    
    def main():
        b(a)
    
    main()
    

    main 应该打印 'hi'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多