倒计时错误

时间:2016-02-10 23:55:11

标签: python tkinter countdown

此代码会产生错误,我不知道为什么或如何解决它?

File "/Users/johnz/Dropbox/PythonWorkspace/BumpersRev1/test3.py", 
  line 7, in countdown
if self.remaining <= 0:
AttributeError: 'int' object has no attribute 'remaining'`

from tkinter import *

# count down timer
def countdown(self, remaining = None):
    if remaining is not None:
        self.remaining = remaining
    if self.remaining <= 0:
        pass
    else:
        self.remaining = self.remaining - 1
        self.after(1000, self.countdown)

def main():
# create a Tk window
    win1 = Tk()
    countdown(90)
    mainloop()

main()

2 个答案:

答案 0 :(得分:3)

您尝试将整数传递到函数倒计时。应该注意self是常规的。它不需要命名,但它是我们通常使用的。但是,因为这不是实例函数(即不是类的一部分),所以您没有理由继承该对象本身。这可以在没有完全自我的情况下完成。

import functools
from Tkinter import *
def countdown(remaining = None):
    if remaining <= 0 or remaining is None:
        pass
    else:
        remaining -= 1
        # Requires a widget instance here....
        # Widget.after(1000, functools.partial(countdown, remaining))

答案 1 :(得分:0)

您必须在after

中发送参数
from tkinter import *

# count down timer
def countdown(remaining, widget):
    print(remaining)

    if remaining > 0:
        remaining = remaining - 1
        widget.after(1000, countdown, remaining, widget)

def main():
    win1 = Tk()
    countdown(90, win1)
    mainloop()

main()

如果win1是全局变量,那么您不必发送widget

from tkinter import *

# count down timer
def countdown(remaining):
    print(remaining)

    if remaining > 0:
        remaining = remaining - 1
        win1.after(1000, countdown, remaining)


# global variables
win1 = Tk()
countdown(90)
mainloop()

BTW:示例after adn在tkinter窗口中显示当前时间: Tkinter Text Animation?