我无法让重启按钮在我的秒表上工作。在 iPhone 上使用 Pythonista
I cannot get the restart button to work on my stopwatch. Using Pythonista on iPhone
import ui
from time import *
start = int(time())
def stop_time(sender):
finish = int(time())
total_time = int(finish - start)
button1 = str("Your time is %i seconds." % (total_time))
sender.title = None
sender.title = str(button1)
如何允许重启按钮更改启动变量?
def restart_time(sender):
start = int(time())
button2 = str("Stopwatch restarted.")
sender.title = None
sender.title = str(button2)
ui.load_view('stop_time').present('sheet')
默认情况下,当您第一次在函数中分配一个标识符时,它会创建一个局部变量,即使存在同名的全局变量也是如此。试试这个:
def restart_time(sender):
global start
start = int(time())
button2 = str("Stopwatch restarted.")
sender.title = None
sender.title = str(button2)
来自the relevant entry in the Python FAQ:
In Python, variables that are only referenced inside a function are
implicitly global. If a variable is assigned a new value anywhere
within the function’s body, it’s assumed to be a local. If a variable
is ever assigned a new value inside the function, the variable is
implicitly local, and you need to explicitly declare it as ‘global’.
import ui
from time import *
start = int(time())
def stop_time(sender):
finish = int(time())
total_time = int(finish - start)
button1 = str("Your time is %i seconds." % (total_time))
sender.title = None
sender.title = str(button1)
如何允许重启按钮更改启动变量?
def restart_time(sender):
start = int(time())
button2 = str("Stopwatch restarted.")
sender.title = None
sender.title = str(button2)
ui.load_view('stop_time').present('sheet')
默认情况下,当您第一次在函数中分配一个标识符时,它会创建一个局部变量,即使存在同名的全局变量也是如此。试试这个:
def restart_time(sender):
global start
start = int(time())
button2 = str("Stopwatch restarted.")
sender.title = None
sender.title = str(button2)
来自the relevant entry in the Python FAQ:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.