我正在尝试编写一个程序,用户可以输入他们希望它离开多少小时和分钟,然后需要当地时间和小时和分钟,并将两者加在一起以产生时间计划结束。
注意:我不希望它将我的输入和当前时间的数字组合成一个字符串。我需要它来将数字加在一起。
当我运行程序时,我收到此错误:
line 30, in alarm_time
alarm_hour = (hour_awake + time.strftime('%H'))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
我的代码:
from tkinter import *
import tkinter
import time
time_now = ''
hour = time.strftime("%H")
minute = time.strftime("%M")
str(hour)
str(minute)
def tick():
global time_now
time_now = time.strftime("%H:%M:%S")
def hours():
global hour_awake
hour_awake = str(input("please enter in how many hours you would like to have the alarm go off in. "))
minutes()
def minutes():
global minute_awake
minute_awake = str(input("please enter in how many minutes you would like to have the alarm go off in. "))
def alarm_time():
alarm_hour = (hour_awake + hour)
alarm_minutes = (minute_awake + minute)
print (alarm_hour, alarm_minutes)
tick()
hours()
alarm_time()
答案 0 :(得分:3)
如果我已正确理解您的问题,请尝试将str()更改为int(),如下所示:
from tkinter import *
import tkinter
import time
time_now = ''
hour = time.strftime("%H")
minute = time.strftime("%M")
int(hour)
int(minute)
def tick():
global time_now
time_now = time.strftime("%H:%M:%S")
def hours():
global hour_awake
hour_awake = int(input("please enter in how many hours you would like to have the alarm go off in. "))
minutes()
def minutes():
global minute_awake
minute_awake = int(input("please enter in how many minutes you would like to have the alarm go off in. "))
def alarm_time():
alarm_hour = (hour_awake + hour)
alarm_minutes = (minute_awake + minute)
print (alarm_hour, alarm_minutes)
tick()
hours()
alarm_time()
答案 1 :(得分:0)
time.strftime('%H')
已经是整数,但是
根据您自己的定义,hour_awake
是一个字符串
因此TypeError。
Python不执行自动类型转换。你必须自己做。所有操作数(变量)必须与“添加”的类型相同:
- 两个字符串将连接成一个字符串,
- 两个整数将执行算术加法。
您需要通过hour_awake
明确地将int(hour_awake)
转换为整数
然后你应该能够将它们加在一起:
alarm_hour = int(hour_awake) + time.strftime('%H')
和
alarm_minutes = int(minute_awake) + minute
这样您就可以将hour_awake
和minute_awake
保留为字符串
或者,如果您不需要将它们存储为字符串,则将input
行更改为:
hour_awake = int(input("please enter in how many hours you would like to have the alarm go off in. "))
..并为minute_awake做同样的事。